Save data in a double for loop with different dimensions
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
mohammed hussein
am 5 Jan. 2026
Kommentiert: mohammed hussein
am 5 Jan. 2026
Dear all
I have a question if you can help me with. I have a program with two loops. In the first loop ( for example, matrix A), after that, I have a second loop (for example, matrix B). In the second loop, I have another caculation depend in each of A ( for example, to find C) in each A for all B. In final i want to save the matrix (C ) required in dimensions A and B.
clear all
clc
A=[0.5 1 1.5 2]
B=[2 4 6 8 10 12 15 18];
for i=1:1:length(A)
A=A(i);
for j=1:1:length(B)
C(:,j)=B(j)+A; % should save matrix C for all j in each i (should be matrx in (4*8))
end
end
2 Kommentare
Akzeptierte Antwort
dpb
am 5 Jan. 2026
Guessing the intent; it isn't totally clear what the expected result would be, but
in
...
for i=1:1:length(A)
A=A(i);
...
The assignment to A wipes out the original A leaving only a single value the first iteration.
Try
A=[0.5 1 1.5 2];
B=[2 4 6 8 10 12 15 18];
C=zeros(numel(A),numel(B)); % preallocate -- will be 4x8 here
for i=1:numel(A) % over A for rows
for j=1:numel(B) % over B for columns
C(i,j)=A(i)+B(j); % build each element individually by row,column
end
end
format bank % only need 2 decimals
disp(C)
This can be done more expeditiously using MATLAB matrix operations --
C=zeros(numel(A),numel(B)); % preallocate -- will be 4x8 here
for i=1:numel(A) % over A for rows
C(i,:)=A(i)+B; % build each row adding A to B vector
end
disp(C)
Or, even more succinctly, don't need any steenkin' loops at all with MATLAB automatic expansion...
C=A.'+B; % add B row vector to A column vector -- expands automagically
disp(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!