Problem with array filling
조회 수: 11 (최근 30일)
이전 댓글 표시
Hi,
I need to do this:
for i=0.1:0.1:360
j(i*10)=2;
end
but I obtain this error message:
??? Attempted to access j(3); index must be a positive integer or
logical.
Could you help me?
Thanks in advance
Thomas
댓글 수: 0
채택된 답변
Image Analyst
2012년 8월 17일
Besides the others all saying to cast your index to integer like this:
for k = 0.1 : 0.1 : 360
jArray1(int32(k * 10)) = int32(2);
end
I also want to say that it's usually recommended not to use i and j (though you can) as variable names since they also are the imaginary variable. Hence my new names in the corrected code above.
Also, there are some other ways that are more probably efficient and "MATLAB-ish" to do what you did, such as the methods below:
jArray2 = 2 * ones(1, 3600, 'int32');
jArray3(1 : 3600) = int32(2);
댓글 수: 0
추가 답변 (4개)
Oleg Komarov
2012년 8월 17일
편집: Oleg Komarov
2012년 8월 17일
sprintf('%.17g', 0.3)
ans =
0.29999999999999999
댓글 수: 0
Matt Fig
2012년 8월 17일
편집: Matt Fig
2012년 8월 17일
The reason you get this error is because of floating point arithmetic.
Look closely:
isequal((0.1:0.1:1)*10,1:10) % NO!
Here is the closer look:
x = (0.1:0.1:1)*10;
x==(1:10) % Notice the third return is a zero, here's why:
fprintf('%.16f\n%.16f\n',x(3),3) % Print out and compare...
댓글 수: 0
Azzi Abdelmalek
2012년 8월 17일
편집: Azzi Abdelmalek
2012년 8월 17일
in matlab index must be a real strict positiv integer
it does'nt accept x(0) or x(-1)
h=zeros(360*10/0.1,1)
for j=0.1:0.1:360
ind=int16(j*10) % convert to integer, for biger number, u can use int32, int64
h(ind)=2;
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 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!