MATLAB Answers

using fscanf to sort x and y values into vectors

5 views (last 30 days)
Caitlin Schmidt
Caitlin Schmidt on 23 Jul 2019
Commented: Walter Roberson on 30 Jul 2019
I have attached the data file I am referencing. I need to separated the x-values and the y-values into two separate vectors. This is what I have created:
function [x,y]= week8_4_1(filepath)
%This function will read from a data file and extract all x and y data
%values, and put them into vectors
if fid==-1
mat=fscanf(fid,'x %f y %f\n',[2,inf]);
if status~=0
disp('File could not be closed');
disp('File closed successfully');
I keep getting an error when I try to run the program saying:
Index in position 1 exceeds array bounds.
Error in week8_4_1 (line 11)
I'm not sure what is wrong with my code. Any help is appreciated!


Show 2 older comments
Walter Roberson
Walter Roberson on 24 Jul 2019
You could attach the data file so that we could examine it.
Caitlin Schmidt
Caitlin Schmidt on 24 Jul 2019
I cannot attach it because it is a .dat file.

Sign in to comment.

Answers (1)

Chidvi Modala
Chidvi Modala on 30 Jul 2019
I see your mat file is empty that could be the reason behind this error. I assume that you are trying to read data from data file by excluding the characters ‘x’, ‘y’ and the data file has data in the below format
x2 y3
x4 y5
Try replacing mat=fscanf(fid,'x %f y %f\n',[2,inf]); with mat = fscanf(fid,[’x’ ‘%f’ ‘ y’ ‘%f\n’],[2 inf]);
You can refer to to see how to skip special characters in file using ‘fscanf’.

  1 Comment

Walter Roberson
Walter Roberson on 30 Jul 2019
I do not see how that change can make any difference. Computing a character vector with [] of static parts that are all character vectors is the same as just hardcoding the complete vector, except hypothetically in cases of errors in the execution engine or JIT

Sign in to comment.


Translated by