Save data in a double for loop with different dimensions
48 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
dpb
2026-1-5,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)
更多回答(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!