Error "Index in position 2 is invalid."
古いコメントを表示
%Heres the code I am working with.
gmat=zeros(118,400);
fid1=fopen('tomo_data.txt','r');
gdata= fscanf(fid1,'%f %f %f',[3,1600]);
for i=1:1600
gmat(gdata(1,i),gdata(2,i)) = gdata(2,i);
end
Heres the error:
Index in position 2 is invalid. Array indices must be positive integers or logical values.
Error in ch5q2b (line 16)
gmat(gdata(1,i),gdata(2,i)) = gdata(2,i);
Attached to this question is the txt file used. Any help would be appriciated.
2 件のコメント
What's your final goal with yoour code? The problem you're facing is that your file has multiple floating points and this is probably what is causing the error of "index in position x is invalid".
The following code is, for instance invalid and has the exact same error as yours:
a = zeros(5,5);
a(1,0.5)
Also, you're creating all your code (vector and for) with predetermined values. This may not be a good practice if your input text change in the future. Instead you could go with something like:
fid1=fopen('tomo_data.txt','r');
gdata= fscanf(fid1,'%f %f %f',[3,1600]);
gmat = zeros(size(gdata));
Therefore, it'd be better if we could try to really understand what you're trying to do :D
Jacob Allen
2022 年 10 月 21 日
回答 (1 件)
The error is because your second index, the column index for gmat, which is gdata(2,i), is 0. That is not a valid index. Indices in MATLAB must be positive integers (or logicals).
gmat = 1:3;
% works
gmat(1,1)
% your error
gmat(1,0)
6 件のコメント
Jacob Allen
2022 年 10 月 21 日
Cris LaPierre
2022 年 10 月 21 日
編集済み: Cris LaPierre
2022 年 10 月 21 日
You haven't explained what you are trying to achieve, so that would be hard to say.
You need to change how you are assigning values into gmat so that the index values are never 0, negative, or decimal values. The code assumes the values of gdata are all valid indices, but many are not.
gmat(gdata(1,i),gdata(2,i))
Jacob Allen
2022 年 10 月 21 日
Cris LaPierre
2022 年 10 月 21 日
That doesn't help explain what you are trying to do with gmat and gdata.
What is gdata? Why are you trying to reshape it from a 3x79 array to an 118x400 array? How do you determine where each value in gdata should go in gmat?
Jacob Allen
2022 年 10 月 23 日
Cris LaPierre
2022 年 10 月 24 日
The error has been explained, but we don't have enough detail to tell you what it should be doing instead.
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!