Creating results from multiple for loops

5 views (last 30 days)
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!

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 8 Sep 2023
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 Comments
Dyuman Joshi
Dyuman Joshi on 11 Sep 2023
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 on 11 Sep 2023
Thank you so much. This was really helpful.. :)

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!