MATLAB Answers

Info

This question is closed. Reopen it to edit or answer.

How to appendant for loop data to new coloum of a matrix

1 view (last 30 days)
Catherine
Catherine on 22 Feb 2017
Closed: MATLAB Answer Bot on 20 Aug 2021 at 17:49
Hi guys, I am having problem storing my new for loop data to a new column of my matrix. For each C value, there should be a set of B values with all A values. I want to store each set of B values to new column in MAB. My current codes overwrite the column:
s=0;
g=0;
for C = 1:0.1:5;
for A = -10:1:10;
B = pi*A*C;
MAB(s+1,1) = A;
MAB(s+1,2) = B;
s = s+1;
end
s = 0;
plot(MAB(:,1),MAB(:,2))
MAC(g+1,1) = C;
MAC(g+1,2) = B;
g = g+1;
end
g=0;
figure
plot(MAC(:,1),MAC(:,2))
Please let me know what I can do. Thanks heaps!

Answers (1)

KSSV
KSSV on 22 Feb 2017
C = 1:0.1:5 ;
A = -10:1:10 ;
MAB = cell(length(C),length(A)) ;
MAC = cell(length(C),1) ;
for i = 1:length(C);
for j = 1:length(A)
B = pi*A(j)*C(i);
MAB{i,j}(j,1) = A(j);
MAB{i,j}(j,2) = B;
end
MAC{i}(i,1) = C(i);
MAC{i}(i,2) = B;
end
NOw MAB, MAC are cells. You can access them.
  1 Comment
Catherine
Catherine on 22 Feb 2017
Hi KSSV, thanks for the reply. I don't know how to access the cell array as each element is a double. But I figured it out at the end which is sort of similar to your code:
s=0;
g=0;
for C = 1:0.1:2;
for A = -10:1:10;
B(s+1,g+1) = pi*A*C;
MAB(s+1,1) = A;
s = s+1;
end
s = 0;
MAC(g+1,1) = C;
g = g+1;
end
g=0;
Which makes the row of corresponds to C values and column corresponds to A values respectively.
Thanks a lot though!

Tags

Community Treasure Hunt

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

Start Hunting!