Storing values from inside the third loop to a variable outside the loops
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi all,
Is it possible to store values from the inside of a third for loop into a variable which is outside the loops? For instance I have this code:
a = 2:1:5;
b = [1 1.2 2 2.3 3 3.3 4 5];
final_data = [];
for ii=1:length(a)
c = rand(3,8);
for jj=1:length(b)
c_data = c(:,jj);
if (a(ii) > b(jj) )
for xx = 1:length(c_data)
final_data(xx,ii) = c_data(xx);
end
end
end
end
and I want the values in 'c_data' to be stored inside 'final_data' as rows (the columns are determined by the value of ' ii ' ) for every 'jj' value. But it so happens that the values get over-written for every ' jj ' loop iteration. Or in other words, I was looking for a way to vertically append c_data to final_data for every jj loop iteration without being overwritten.
Thanks
채택된 답변
Voss
2022년 5월 14일
Maybe something like this?
a = 2:1:5;
b = [1 1.2 2 2.3 3 3.3 4 5];
na = numel(a);
nb = numel(b);
nc = 3;
final_data = NaN(nb*nc,na);
for ii=1:na
c = rand(nc,nb) % showing c on command-line for reference
for jj=1:nb
if (a(ii) > b(jj))
final_data((jj-1)*nc+(1:nc),ii) = c(:,jj);
end
end
end
disp(final_data)
댓글 수: 5
Voss
2022년 5월 15일
You can avoid having any NaNs above any non-NaN c values by keeping track of how many rows have been written to in each column:
a = 2:1:5;
% b = [1 1.2 2 2.3 3 3.3 4 5];
b = [1 1.2 4 5 3 3.3 2 2.3];
na = numel(a);
nb = numel(b);
nc = 3;
final_data = NaN(nb*nc,na);
last_row = zeros(1,na);
for ii=1:na
c = rand(nc,nb) % showing c on command-line for reference
for jj=1:nb
if (a(ii) > b(jj))
final_data(last_row(ii)+(1:nc),ii) = c(:,jj);
last_row(ii) = last_row(ii)+nc;
end
end
end
disp(final_data);
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!