Creating results from multiple for loops

조회 수: 5 (최근 30일)
Michael Henry
Michael Henry 2023년 9월 8일
댓글: Michael Henry 2023년 9월 11일
Hi all
I have a problem with creating results from multiple for loops. What I am looking to is to create a matrix of row and columns (A1 and A2 in my work below) then for every cell (which is basically a pair of A1 and A2) make a new equation U1 which contains this pair, and a new variable (a) which length is different from the original variables. Finally, I need to find the maximum value of all possible combinations.
I tried the following. I know that my work is correct up to the line of for k = 1...., then I am not sure how to create a new vector of results. In other words, what I need is, for every given pair of A1 and A2, calculate U for all values of a and then store these values in vectors.
---------------
A1 = 1:1:5;
A2 = 1:1:5;
a = 0:0.1:1;
for row = 1:length(A1)
for col = 1:length(A2)
for k = 1: length(a)
U(row,col) = (A1(row) + A2(col))*a(k);
end
end
end
--------------
I hope my question is clear. Many thanks in advance!

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 9월 8일
Do you mean like this -
A1 = 0:1:5;
A2 = 0:1:5;
a = 0:0.1:1;
a = shiftdim(a,-1);
%or
%a = permute(a,[2 3 1]);
out = (A1+A2').*a;
m = max(out,[],'all')
m = 10
  댓글 수: 16
Dyuman Joshi
Dyuman Joshi 2023년 9월 11일
A1 = 1:5;
A2 = 1:5;
a = 0:0.1:1;
n1 = numel(A1);
n2 = numel(A2);
%Preallocation
%To store the output
C = cell(n1,n2);
%To store the maximum value of each cell
m = zeros(n1,n2);
%Threshold for comparison, random value for example
thresh = 2.5;
for row=1:n1
for col=1:n2
vec = (A1(row)+A2(col))*a;
%Set values lower than threshold to be 0
vec(vec<thresh) = 0;
%Continue with assignment
C{row,col} = vec;
end
end
C
C = 5×5 cell array
{[ 0 0 0 0 0 0 0 0 0 0 0]} {[ 0 0 0 0 0 0 0 0 0 2.7000 3]} {[ 0 0 0 0 0 0 0 2.8000 3.2000 … ]} {[ 0 0 0 0 0 2.5000 3 3.5000 4 … ]} {[ 0 0 0 0 0 3 3.6000 4.2000 … ]} {[ 0 0 0 0 0 0 0 0 0 2.7000 3]} {[ 0 0 0 0 0 0 0 2.8000 3.2000 … ]} {[ 0 0 0 0 0 2.5000 3 3.5000 4 … ]} {[ 0 0 0 0 0 3 3.6000 4.2000 … ]} {[0 0 0 0 2.8000 3.5000 4.2000 … ]} {[0 0 0 0 0 0 0 2.8000 3.2000 … ]} {[ 0 0 0 0 0 2.5000 3 3.5000 4 … ]} {[ 0 0 0 0 0 3 3.6000 4.2000 … ]} {[0 0 0 0 2.8000 3.5000 4.2000 … ]} {[ 0 0 0 0 3.2000 4 4.8000 … ]} {[0 0 0 0 0 2.5000 3 3.5000 4 … ]} {[ 0 0 0 0 0 3 3.6000 4.2000 … ]} {[0 0 0 0 2.8000 3.5000 4.2000 … ]} {[ 0 0 0 0 3.2000 4 4.8000 … ]} {[ 0 0 0 2.7000 3.6000 4.5000 … ]} {[ 0 0 0 0 0 3 3.6000 4.2000 … ]} {[0 0 0 0 2.8000 3.5000 4.2000 … ]} {[ 0 0 0 0 3.2000 4 4.8000 … ]} {[ 0 0 0 2.7000 3.6000 4.5000 … ]} {[ 0 0 0 3.0000 4 5 6 7 8 9 10]}
Michael Henry
Michael Henry 2023년 9월 11일
Thank you so much. This was really helpful.. :)

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

추가 답변 (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