How to create a matrix from given vectors
Ältere Kommentare anzeigen
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
Akzeptierte Antwort
Weitere Antworten (2)
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);
1 Kommentar
Andrei Bobrov
am 25 Okt. 2012
+1
Azzi Abdelmalek
am 25 Okt. 2012
Bearbeitet: Azzi Abdelmalek
am 25 Okt. 2012
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 Kommentare
Jason
am 25 Okt. 2012
Azzi Abdelmalek
am 25 Okt. 2012
there are no 4, just one: out
Jason
am 25 Okt. 2012
Jason
am 25 Okt. 2012
Azzi Abdelmalek
am 25 Okt. 2012
just extract
out(:,1:3)
Kategorien
Mehr zu Logical finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!