필터 지우기
필터 지우기

Index in position 2 exceeds array bounds

조회 수: 7 (최근 30일)
Camila Gill
Camila Gill 2020년 1월 16일
답변: Sindar 2020년 1월 16일
Given a .txt file of x,y,z values. Must read data, then plot.
In the plot command: what is position 2? and how do I correct the error?
figure(1)
clf
fp=fopen('shoesolelayers.txt','r');
nlayers=1;
for l=1:nlayers
sline=fgetl(fp);
[xpts,pnts]=sscanf(sline,'%f');
sline=fgetl(fp);
[ypts,pnts]=sscanf(sline,'%f');
sline=fgetl(fp);
[zpts,pnts]=sscanf(sline,'%f');
sline=fgetl(fp);
scanvecs(l)={[xpts ypts zpts]};
end
fclose(fp);
% PLOTS FIRST LAYER IN FIGURE(1) WINDOW
what=scanvecs(l);
% plot(layl(1,:),layl(2,:),'b');
plot(what(:,1),what(:,2),'b');
**Index in position 2 exceeds array bounds (must not exceed 1).
  댓글 수: 1
Mohammad Sami
Mohammad Sami 2020년 1월 16일
when you are indexing into an array. position 2 is the second dimension (columns).
array(position1,position2)
In your case whichever variable you are using only has a single column.

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

답변 (1개)

Sindar
Sindar 2020년 1월 16일
scanvecs is a 1xl cell, so
what=scanvecs(l);
makes "what" also a 1x1 cell (containing the last set of data). Indexing what(:,2) doesn't find anything.
If instead you have:
what=scanvecs{l};
then "what" is the contents of the last cell in scanvecs, so it is a matrix -- specifically [xpts ypts zpts] for the last l. This should resolve your error.
Other notes:
  • 'l' is a poor choice of variable name, since it looks so much like '1'. Personally, I like 'ind' as an index variable'
  • "what" is a built-in Matlab command, so you should rename that variable to avoid issues later
  • Do you mean to only access the last element? If yes, I'd use nlayers instead of relying on the loop index variable. If not, you'll need to adjust your code somewhat. "PLOTS FIRST LAYER IN FIGURE(1) WINDOW" suggests you might want the first element instead, so use scanvecs{1}
  • Is nlayers normally 1? If so, why are you looping?
  • There are cleaner and easier ways of reading data. I recommend reading the documentation for readtable, textscan, and fscanf

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by