For loop with decimal increment not seen as integer or logical value
이전 댓글 표시
Goal:
- Have for loop repeatedly create matrices of random integers
- Create new matrix where columns = variance for each row of random integer matrices
- Compare variance to increment ranging from 0:0.01:4 (0-4 in increments of 0.01) and retain each matrix of 0s and 1s generated this way
The following code produces the desired results when the increment = 1 (not 0.01)
T = 10;
W = zeros(3,10);
for trial = 1:T
mtest = randi([1,5],3,4)
W(:,trial) = var(mtest,0,2);
end
minc = zeros(3,10,5);
for mindex = 0:1:4
minc(:,:,mindex+1) = W >= mindex
end
Problem 1: The same code does not work when the increment is set to 0.01:
linc = zeros(3,10,401);
for lindex = 0:0.01:4
linc(:,:,lindex+1) = W >= lindex
end
Error = Index in position 3 is invalid. Array indices must be positive integers or logical values.
Problem 2: After much reading, I think the problem is that "lindex+1" produces indices of 1.01, 1.02...etc. Yet both of the below solutions produce the same error.
Solution 1: Add 1 to remove 0 from index; multiply by 100 such that index should proceed as 100, 101, 102...etc.
linc = zeros(3,10,401);
for lindex = 0:0.01:4
linc(:,:,(lindex+1)*100) = W >= lindex
end
Solution 2: Start index at 0.01 instead of 0 and multiply by 100 such that index should proceed as 100, 101, 102...etc.
linc = zeros(3,10,401);
for lindex = 0.01:0.01:4
linc(:,:,lindex*100) = W >= lindex
end
Why does the code work if increment = 1 but not 0.01? How can I fix this? Thank you in advance, this is a wonderful community.
댓글 수: 3
Sindar
2020년 1월 23일
It's not clear to me why your solutions aren't working, but the method KSSV suggests is easier and more reliable. In fact, I find it can often be worthwhile to iterate over a set of indices even when you don't plan to use your variable as an index. It just makes things a bit cleaner and easier to test (e.g., looping only over some of the data)
May_the_degrees_of_freedom_be_with_you
2020년 1월 23일
May_the_degrees_of_freedom_be_with_you
2020년 1월 23일
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!