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 个评论
Stephen23
Stephen23 2026-1-5,19:45
This is MATLAB:
A = [0.5,1,1.5,2];
B = [2,4,6,8,10,12,15,18];
C = A(:)+B
C = 4×8
2.5000 4.5000 6.5000 8.5000 10.5000 12.5000 15.5000 18.5000 3.0000 5.0000 7.0000 9.0000 11.0000 13.0000 16.0000 19.0000 3.5000 5.5000 7.5000 9.5000 11.5000 13.5000 16.5000 19.5000 4.0000 6.0000 8.0000 10.0000 12.0000 14.0000 17.0000 20.0000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

请先登录,再进行评论。

采纳的回答

dpb
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)
2.50 4.50 6.50 8.50 10.50 12.50 15.50 18.50 3.00 5.00 7.00 9.00 11.00 13.00 16.00 19.00 3.50 5.50 7.50 9.50 11.50 13.50 16.50 19.50 4.00 6.00 8.00 10.00 12.00 14.00 17.00 20.00
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)
2.50 4.50 6.50 8.50 10.50 12.50 15.50 18.50 3.00 5.00 7.00 9.00 11.00 13.00 16.00 19.00 3.50 5.50 7.50 9.50 11.50 13.50 16.50 19.50 4.00 6.00 8.00 10.00 12.00 14.00 17.00 20.00
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)
2.50 4.50 6.50 8.50 10.50 12.50 15.50 18.50 3.00 5.00 7.00 9.00 11.00 13.00 16.00 19.00 3.50 5.50 7.50 9.50 11.50 13.50 16.50 19.50 4.00 6.00 8.00 10.00 12.00 14.00 17.00 20.00

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by