MATLAB Answers

how to store values into array/matrix with different number of rows and only one column

조회 수: 2(최근 30일)
Khairul Nur
Khairul Nur 2021년 8월 6일
댓글: Khairul Nur 2021년 8월 9일
Hi, how i want to store values from loop which has only 1 cols but may have different numbers rows.
For example, in 1st loop the result is
1
2
Meanwhile 2nd loop the results is
1
2
3
Thus, i want to store it as:
1 1
2 2
0 3
Is it possible? Since within the loop...the row can be any numbers.

채택된 답변

Rik
Rik 2021년 8월 6일
편집: Rik 2021년 8월 6일
It is best to pre-allocate your output array as close to the size you think you need, because extending a matrix hurts performance substantially.
cols=2;
est_rows=5;%estimate of the largest number of rows
result=zeros(est_rows,cols);keep_rows=0;
for col=1:2
if col==1 ,part_result=(1:2).';
elseif col==2,part_result=(1:3).';
end
keep_rows=max(keep_rows,numel(part_result));
result(1:numel(part_result),col)=part_result;
end
result((keep_rows+1):end,:)=[];%will only crop unused rows
result
result = 3×2
1 1 2 2 0 3
  댓글 수: 1
Khairul Nur
Khairul Nur 2021년 8월 9일
Tq for the code and idea...edit it to fit mine..and its working great..tq rik!

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

추가 답변(0개)

태그

Community Treasure Hunt

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

Start Hunting!

Translated by