create a matrix with numbers from vector

1 次查看(过去 30 天)
i have a vector as
v = [ 1 1 1 2 2 2 3 3 4]
i wanted to create a new matrix as
M = [
1 1 1 0 0 0 0 0 0;
0 0 0 1 1 1 0 0 0;
0 0 0 0 0 0 1 1 0;
0 0 0 0 0 0 0 0 1];
how to do it?

采纳的回答

madhan ravi
madhan ravi 2019-2-13
v = [1 1 1 2 2 2 3 3 4];
u=unique(v);
R=arrayfun(@(x)v==u(x),1:numel(u),'un',0);
M=+vertcat(R{:})
Gives:
M =
1 1 1 0 0 0 0 0 0
0 0 0 1 1 1 0 0 0
0 0 0 0 0 0 1 1 0
0 0 0 0 0 0 0 0 1

更多回答(2 个)

madhan ravi
madhan ravi 2019-2-13
Simpler:
M = +(v==unique(v).')

KSSV
KSSV 2019-2-13
N = zeros(3,3,3) ;
for i = 1:3
N(i,:,i) = 1 ;
end
M = reshape(N,3,[])
  2 个评论
KSSV
KSSV 2019-2-13
Give Example....by the way what is use of v here?
KSSV
KSSV 2019-2-13
v = [ 1 1 1 2 2 2 3 3 4] ;
v = reshape(v,[],3)' ;
N = zeros(3,3,3) ;
for i = 1:3
N(i,:,i) = v(i,:) ;
end
M = reshape(N,3,[])

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by