Populate columns of matrix without for loop using input from a vector of intergers

조회 수: 1 (최근 30일)
I am looking for a way to generate a target matrix for the neural network toolbox using labeled data where each class is represented in an vector of integers.
Example:
X =
[0
2
1
2
3]
I need this in the form
X = [ 1 0 0 0
0 0 1 0
0 1 0 0
0 0 1 0
0 0 0 1]
Is it possible to do this without a loop?
Thanks

채택된 답변

José-Luis
José-Luis 2017년 7월 7일
편집: José-Luis 2017년 7월 7일
X=[0, 2, 1, 2, 3];
numCols = max(X) + 1;
result = zeros(numel(X),numCols);
idx = sub2ind(size(result),1:numel(X),X+1 );
result(idx) = 1
To go back:
[~, back_result] = find(result);
back_result = back_result - 1

추가 답변 (1개)

Greg Heath
Greg Heath 2017년 7월 7일
>> clear all
classindices = [1 3 5 4 2 ];
classmatrix = full(ind2vec(classindices))
classmatrix =
1 0 0 0 0
0 0 0 0 1
0 1 0 0 0
0 0 0 1 0
0 0 1 0 0
Hope this helps.
Greg

카테고리

Help CenterFile Exchange에서 Sequence and Numeric Feature Data Workflows에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by