how can I append two or more matrices inside For Loop?

In the following code; I transform decimal matrix to binary and I want to save all the representations in same matrix whcih simply append all matrices in one general matrix. Note that, number of columns is fixed, rows are only changing. but bbecause I am using for loop, the new representation replace the old one. How can I save all of them in the same matrix?
x=[5 -3 -1 -1 -1]; % decimal to binary representation
b = dec2bin(0:2^numel(x)-1)=='1';
y=[5 -1;5 -2];
r=size(y,1); % number of rows is more importnat
for n=1:r
z1 = b(b*x'==y(n,1),:); % binary represntation for column 1
z2 = b(b*x'==y(n,2),:); % binary represntation for column 2
end
the result I want for z1 is the reprsentation of 5 & 4:
z1=[1 0 0 0 0;1 0 0 0 1; 1 0 0 1 0; 1 0 1 0 0] but using the above code I just got represntation for last iteration only which is 4; z1=[1 0 0 0 1; 1 0 0 1 0; 1 0 1 0 0]
y matrix rows may change from 1 ---> 10 rows depends in the user and also the element values are changing, I have this part done!
So my only concern is how to save all representations in one matrix??

 採用された回答

Star Strider
Star Strider 2016 年 9 月 19 日

1 投票

I am not certain what you want to do.
Experiment with this to get the result you want:
x=[5 -3 -1 -1 -1]; % decimal to binary representation
b = dec2bin(0:2^numel(x)-1)=='1';
y=[5 -1;5 -2];
r=size(y,1); % number of rows is more important
z1 = []; % Initialise ‘z1’
z2 = []; % Initialise ‘z2’
for n=1:r
z1 = [z1; b(b*x'==y(n,1),:)]; % binary represntation for column 1
z2 = [z2; b(b*x'==y(n,2),:)]; % binary represntation for column 2
end

4 件のコメント

JacobM
JacobM 2016 年 9 月 19 日
編集済み: JacobM 2016 年 9 月 19 日
Yes, that is exactly what I want, thank you very much. but if I want z1 to be only [1 0 0 0 0] instead of [1 0 0 0 0;1 0 0 0 0] (no rows duplication) what do you suggest to use?
by the way, y matrix is changing and may take more rows. so each time z1 should not duplicate the representation of any equal element like this case I have here.
Star Strider
Star Strider 2016 年 9 月 19 日
My pleasure.
The duplicates appear to be determined by your ‘y’ matrix. It has duplicates in the first column, so ‘z1’ will have duplicate rows.
You can eliminate all duplicated rows after the loop with the unique function and 'rows' option:
z1 = unique(z1, 'rows');
JacobM
JacobM 2016 年 9 月 20 日
Great! thank you so much Star Strider. I really appreciate it.
Star Strider
Star Strider 2016 年 9 月 20 日
As always, my pleasure!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2016 年 9 月 19 日

コメント済み:

2016 年 9 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by