How to create a matrix from given vectors

I have a vector A= [ 2 4 1 3 ]
How can you create a matrix which are the length of the vector values with ones. the rest zeros?
i.e I want
B= [1 1 1 1; 1 1 0 1; 0 1 0 1; 0 1 0 0]
Regards
jason

2 件のコメント

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 25 日
it's not clear
Jason
Jason 2012 年 10 月 25 日
sorry - my first value in A is 2. So I want my first column of B to have 2 two entities both ones. A(2)=4 so i want my second column of B to have 4 values of ones. A(3)=1 so my thrid column of B only has the one 1. Overall I need this to be a matrix. So wherever there is no 1s present I want zeros.
my vecotrs of A will be a lot larger than demonstrated here so an automated way to create teh ones in the correct place for each value will be great.
Still not sure if this will be clear enough. I'm a novice and don't know all the terms.
jason

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

 採用された回答

Andrei Bobrov
Andrei Bobrov 2012 年 10 月 25 日

0 投票

C = zeros(max(A),numel(A));
C(A + (0:numel(A)-1)*size(C,1)) = 1;
B = flipud(cumsum(C(end:-1:1,:)));

5 件のコメント

Jason
Jason 2012 年 10 月 25 日
exactly what I mean thanks.
Jason
Jason 2012 年 10 月 25 日
This method "falls" over when some values of zero are in the A matrix? i.e. if A=[5 3 4 0 8] it actually effects the column before.
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 25 日
Then try my code
Matt Fig
Matt Fig 2012 年 10 月 25 日
編集済み: Matt Fig 2012 年 10 月 25 日
This fixes Andrei's code for when A has a zero (a possibility that should have been mentioned in the original post!)
C = zeros(max(A),numel(A));
idx = A + (0:numel(A)-1)*size(C,1);
C(idx(A>0)) = 1;
C = flipud(cumsum(C(end:-1:1,:)));
Andrei Bobrov
Andrei Bobrov 2012 年 10 月 25 日
Thanks Matt.

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

その他の回答 (2 件)

Matt Fig
Matt Fig 2012 年 10 月 25 日
編集済み: Matt Fig 2012 年 10 月 25 日

1 投票

Here is the obligatory one liner. It works whether or not A has a zero.
D = cumsum(ones(max(A),length(A))) <= A(ones(1,max(A)),:);
Or (slower but memory efficient):
D = bsxfun(@(x,y) x<=y,(1:max(A)).',A);
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 25 日
編集済み: Azzi Abdelmalek 2012 年 10 月 25 日

0 投票

A= [ 2 4 1 3 ];
n=length(A);
s=meshgrid(1:n);
out=cell2mat(arrayfun(@(x,y) y<=A(x),s,s','un',0))

5 件のコメント

Jason
Jason 2012 年 10 月 25 日
Thanks Azzi and sorry about the confusion. This however produces 4 matrices where I only needed the one. thanks
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 25 日
there are no 4, just one: out
Jason
Jason 2012 年 10 月 25 日
sorry yes, this works thanks :)
Jason
Jason 2012 年 10 月 25 日
is there a way to have it as a 6 by 3 matrix rather than a 6 by 6 matrix?
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 25 日
just extract
out(:,1:3)

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

カテゴリ

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by