array to matrix transformation with size[ length of array , largest element in array]

조회 수: 2 (최근 30일)
I have an array [1 1 2 3 1 2 1 ] I want to generate a matrix of size [7x3] as length of array is 7 and maximum element is 3. for example the output look like this
A=[1 0 0
1 0 0
0 1 0
0 0 1
1 0 0
0 1 0
1 0 0]
showing that the 1st element of array assigns 1 to the corresponding column in A. for example the 1st element is 1 so row 1 and column 1 gets value 1, the 3rd element is 2 so row 3 column 2 gets value 1 and so on. Is there any way to do so? I tried diag[array] but it gives a 7x7 matrix

채택된 답변

Stephen23
Stephen23 2017년 1월 8일
편집: Stephen23 2017년 1월 8일
No need to for any ugly loops, just use sub2ind:
>> C = [1,1,2,3,1,2,1];
>> R = 1:numel(C);
>> Z = zeros(R(end),max(C));
>> Z(sub2ind(size(Z),R,C)) = 1
Z =
1 0 0
1 0 0
0 1 0
0 0 1
1 0 0
0 1 0
1 0 0

추가 답변 (2개)

Image Analyst
Image Analyst 2017년 1월 8일
Did you try the obvious brute force way:
array = [1 1 2 3 1 2 1 ]
lengthA = length(array)
maxA = max(array)
A = zeros(lengthA, maxA)
for k = 1 : lengthA
A(k, array(k)) = 1;
end
A % Report to the command window

Steven Lord
Steven Lord 2017년 1월 8일
If you want this to be a full array, use accumarray. If the number of rows and/or columns is expected to be large consider using sparse.
% Full
cols = [1 1 2 3 1 2 1 ];
cols = cols(:);
rows = (1:length(cols)).';
A = accumarray([rows, cols], 1)
% Sparse
cols = [1 1 2 3 1 2 1 ];
S = sparse(1:length(cols), cols, 1)
isequal(A, full(S))

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by