How to dynamically update the matrix ?

Hello Guys,
I have to generate matrix A=[-1 0 c1; 0 -1 c2] dynamically, for example if c1=[1 1 2 2] & c2=[3 3 4 4] are 1d arrays and if its length change after every execution of loop then the output of matrix A will increase automatically after increase in length of c1 & c2 arrays, for example in case of above example the output of A will be like...
A = [-1 0 1;
0 -1 3;
-1 0 1;
0 -1 3;
-1 0 2;
0 -1 4;
-1 0 2;
0 -1 4;]
How do i write this type of matrix dynamically ?

 採用された回答

Weird Rando
Weird Rando 2016 年 5 月 8 日
編集済み: Weird Rando 2016 年 5 月 8 日

0 投票

This only works if c1 and c2 have the same length
A = [];
c1=[1 1 2 2];
c2=[3 3 4 4];
nloop = length(c1);
for ii = 1:nloop
A=[A;-1 0 c1(ii); 0 -1 c2(ii)]
end

4 件のコメント

Ahsan Abbas
Ahsan Abbas 2016 年 5 月 8 日
Thank you Scott for your answer, but i have the c1 & c2 in cell format, like c1{1}=1, c1{2}=1... and c2{1}=3, c2{2}=3... its making the matrix A in cell format like this
A =
[-1] [ 0] [1]
[ 0] [-1] [3]
how can i solve this problem ? Thanks
Ced
Ced 2016 年 5 月 8 日
You can transform c1 and c2 into matrices before concatenation. There is no need for the for loop.
A = [ 1 2 ; 3 4];
c1 = {1,1,2,2};
c2 = {3,3,4,4};
c1_num = cell2mat(c1);
c2_num = cell2mat(c2);
A = horzcat(A,[c1_num; c2_num]);
or, directly
A = [ 1 2 ; 3 4];
c1 = {1,1,2,2};
c2 = {3,3,4,4};
A = [ A cell2mat([c1 ; c2]) ]
Note that c1_num and c2_num must have the same number of columns, and their total number of rows should equal the number of rows of A. Also, the cells must only contain numerical scalars, but I suppose that's fairly obvious.
Image Analyst
Image Analyst 2016 年 5 月 8 日
There is also no need, that you've shown so far, for a cell array. A simple numerical array would be much simpler and easier.
Ahsan Abbas
Ahsan Abbas 2016 年 5 月 8 日
Thank you Ced & Image Analyst for your responses, specially for cell2mat.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by