Creating results from multiple for loops
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Michael Henry
am 8 Sep. 2023
Kommentiert: Michael Henry
am 11 Sep. 2023
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!
0 Kommentare
Akzeptierte Antwort
Dyuman Joshi
am 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')
16 Kommentare
Dyuman Joshi
am 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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

