Save data in a double for loop with different dimensions
50 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
mohammed hussein
le 5 Jan 2026 à 17:10
Commenté : mohammed hussein
le 5 Jan 2026 à 20:44
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 commentaires
Stephen23
le 5 Jan 2026 à 19:45
This is MATLAB:
A = [0.5,1,1.5,2];
B = [2,4,6,8,10,12,15,18];
C = A(:)+B
Réponse acceptée
dpb
le 5 Jan 2026 à 17:43
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)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!