Creating results from multiple for loops
조회 수: 5 (최근 30일)
이전 댓글 표시
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
채택된 답변
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')
댓글 수: 16
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 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!

