0

I am trying to open a text file in MATLAB and plot it in a graph. The following is my code:

%% Get the data 
[filename, pathname] = uigetfile('*txt', 'Pick text file');
x=filename(:,1);
y=filename(:,2);
plot(x,y);

But each time I run it, I get following error:

Error using plot
Invalid first data argument.
Error in readtxtfile (line 5)
plot(x,y); 

The text file that I imported has 2 rows. I am planning to plot the first row with the second say plot (row 1, row 2) in MATLAB.

1 Answer 1

1

You have the name of the file stored in filename combined with the path to the directory where the file is stored in pathname but you actually haven't read any of the contents. To do that, the easiest thing would be to use dlmread. I'm assuming your text file is properly formatted to have two rows of data as you stated. If this is the case, you need to change the way you're indexing into your data. You have it indexing entire columns instead of rows so you need to flip the indexing in your code. Also, you need a call to dlmread, then access the columns of the resulting matrix:

%% Get the data 
[filename, pathname] = uigetfile('*txt', 'Pick text file');
data = dlmread(fullfile(pathname, filename));
x=data(1,:);
y=data(2,:);
plot(x,y);

Notice that I made the full path to your file to use fullfile because using uigetfile allows you to read in a file from anywhere on your computer so we make sure that we capture the full path to your file. Again to reiterate, pathname is the directory of where the file is contained and filename is the name of the file contained in the directory.

Sign up to request clarification or add additional context in comments.

3 Comments

this code works I was able to plot it together... but what I got was just a straight line plot which I was not looking for I am not sure how that happened I feel it didn't read the values in the txt file
it worked now by the following modifications x=data(:,1); y=data(:,2);
You said your text file had two ROWS, not COLUMNS. in the future, make sure you know what their differences are. That's why I changed the code to be so compared to your original.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.