How to store values from a for loop and starting a new row after every 3rd iteration?

조회 수: 10 (최근 30일)
Hello, I am looking to populate a [65x3] matrix from a for loop where after every third itiration a new row will begin so that it looks something like this:
[3, 7, 9
11, 3, 4]
%This is my current code for storing values in a [65x3] matrix.
RARmat = zeros(65, 3)
for ii = 1:65
RARatio = AUC/RA;
disp(RARatio)
% RAR Matrix
RARmat(ii, :) = RARatio;
end
I recieved help to create this code in an earlier questions. In the comments I attempted to ask this as a follow up question if you would like to view it the link is here: https://www.mathworks.com/matlabcentral/answers/481516-store-values-from-a-for-loop-into-a-matrix
I would really appreciate any help with this. Thank you in advance!

채택된 답변

the cyclist
the cyclist 2019년 9월 22일
편집: the cyclist 2019년 9월 22일
RARmat = zeros(65, 3);
for ir = 1:65
for ic = 1:3
RARmat(ir,ic) = rand();
end
end
The inner loop in this code works across the columns, and then after the third column is filled in, the inner loop is done. The outer loop works down the rows. Is that what you mean?
(I'm just filing in a random value in each element.)
  댓글 수: 2
the cyclist
the cyclist 2019년 9월 22일
편집: the cyclist 2019년 9월 22일
Happy to help. For your awareness, though, one great aspect of MATLAB is the ability to write "vectorized" code. For example, the above code could have been written with only one for loop, like this:
RARmat = zeros(65, 3);
for ir = 1:65
RARmat(ir,:) = rand(1,3);
end
or even with no for loops at all, like this:
RARmat = rand(65,3);
where you don't even need the preallocation step.
Of course, your ability to vectorize will be dependent on exactly what you need to fill in.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by