using fscanf to sort x and y values into vectors

조회 수: 2 (최근 30일)
Caitlin Schmidt
Caitlin Schmidt 2019년 7월 23일
댓글: Walter Roberson 2019년 7월 30일
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
[fid,msg]=fopen(filepath);
if fid==-1
disp(msg);
else
mat=fscanf(fid,'x %f y %f\n',[2,inf]);
x=mat(1,:);
y=mat(2,:);
status=fclose(fid);
if status~=0
disp('File could not be closed');
else
disp('File closed successfully');
end
end
end
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)
x=mat(1,:);
I'm not sure what is wrong with my code. Any help is appreciated!
  댓글 수: 5
Caitlin Schmidt
Caitlin Schmidt 2019년 7월 24일
I cannot attach it because it is a .dat file.
Walter Roberson
Walter Roberson 2019년 7월 24일
See my response on your other question

댓글을 달려면 로그인하십시오.

답변 (1개)

Chidvi Modala
Chidvi Modala 2019년 7월 30일
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 https://www.mathworks.com/help/matlab/ref/fscanf.html to see how to skip special characters in file using ‘fscanf’.
  댓글 수: 1
Walter Roberson
Walter Roberson 2019년 7월 30일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by