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

 채택된 답변

Steven Lord
Steven Lord 2022년 1월 5일
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)
f = 8×3 table
cycle temp ind _____ ____ ___ 1 1 1 1 2 1 2 4 1 2 5 1 1 1 2 1 8 2 2 3 2 2 4 2
I'm not entirely sure your nested loops do what you want, but I think what you want is something like this:
tab2 = groupsummary(f, ["ind", "cycle"], 'max', 'temp')
tab2 = 4×4 table
ind cycle GroupCount max_temp ___ _____ __________ ________ 1 1 2 2 1 2 2 5 2 1 2 8 2 2 2 4
Use the ind and cycle variables in your table f as the grouping variables and operate on the data variable temp, computing the summary statistic max. Looking at row 3 of tab2, the values of temp for ind == 2 and cycle == 1 in f are 1 and 8 and indeed the maximum of those two values is the 8 in row 3 of the variable max_temp in tab2.

추가 답변 (1개)

Rik
Rik 2022년 1월 5일
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)
ans = 3×2
2 5 8 3 NaN 4
(I changed the last element of ind to show you the rows and columns)

댓글 수: 1

this seems like a clever solution! But is there a way to get it working with the loop? Since I want to store the values in a table

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

카테고리

도움말 센터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!

Translated by