Saving values from a for loop in a table
이전 댓글 표시
Hey! I am trying to use a loop within a loop to extract maximum temperature for a specified cycle and index. So basically I first try to find rows for a given index and then use the second for loop to find maximum temperature in a specified cycle within that index. However, MATLAB seems to overwrite the values and only stored the last iteration in my table. What am I doing wrong?
Code:
temp = [1;2;4;5;1;8;3;4]; % temperature
ind = [1;1;1;1;2;2;2;2]; % index
cycle = [1;1;2;2;1;1;2;2]; % cycle
f = table(cycle,temp,ind);
in = unique(ind);
inx = unique(cycle);
tab = table;
for i = 1:length(in)
rows = find( ind == in(i))
for j = 1:length(inx)
tab.tmax(j) = max(f.temp(j))
end
end
채택된 답변
추가 답변 (1개)
Your index only depends on j, so it will overwrite all previous results.
Why don't you use a rectangular array to hold the maximum temperature?
temp = [1;2;4;5;1;8;3;4]; % temperature
ind = [1;1;1;1;2;2;2;3]; % index
cycle = [1;1;2;2;1;1;2;2]; % cycle
accumarray([ind cycle],temp,[],@max,NaN)
(I changed the last element of ind to show you the rows and columns)
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!