Linear Problem Matrix without For Loop

조회 수: 7 (최근 30일)
Andreas
Andreas 2015년 1월 22일
댓글: Andreas 2015년 1월 22일
Hello all, I have a problem. Suppose I have a matrix like this:
K= [1 2 4 3 4 6 ]
And I want to end with a matrix like this
L=[1 0 0 0 0 ; 0 1 0 0 0 ; 0 0 0 1 0 ; 0 0 1 0 0 ; 0 0 0 1 0 ; 0 0 0 0 1]
As you can see the number of columns is the size of unique(K) and row is the length(K) How can I create a matrix like L WITHOUT using for.? I tried ind2sub but I failed.* * * * Maybe a solution could be to have a matrix like this
U= [1 2 4 3 4 5 ; 1 2 4 3 4 6]
where the first row is the index. Thank you all!!
  댓글 수: 1
Guillaume
Guillaume 2015년 1월 22일
The number of columns is the max of K not the size of unique(K)

댓글을 달려면 로그인하십시오.

채택된 답변

Andreas
Andreas 2015년 1월 22일
Hello all.! thank you for your answers!! I think I found it,with your help.
K = [1 2 4 3 4 6 ];
[~,n]=ismember((K),unique(K));
L=zeros(length(K),length(unique(K)))
L(sub2ind(size(L), 1:length(K(1,1:end)),n))= 1
if there's something better I'll be glad to see it.! Thank you all!
  댓글 수: 4
Guillaume
Guillaume 2015년 1월 22일
편집: Guillaume 2015년 1월 22일
Well, I'd assume 6 means 6th column, 10 mean 10th column, etc.
If the numbers don't mean anything other than specifying an ordering, then do:
[~, ~, K] = unique(K);
before any of my answers.
K = 'ACPIPZ'; %you can even use letters since the numbers have no meaning.
%challenge: find an English word that gives the same result.
[~, ~, K] = unique(K);
L = full(sparse(1:numel(K), K, 1))
is still a lot simpler.
Andreas
Andreas 2015년 1월 22일
amazing.!thank you very much!!

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Guillaume
Guillaume 2015년 1월 22일
편집: Guillaume 2015년 1월 22일
K = [1 2 4 3 4 6 ];
L = zeros(numel(K), max(K));
L(sub2ind(size(L), 1:numel(K), K)) = 1
or using sparse matrices:
L = full(sparse(1:numel(K), K, 1))
or using accumarray:
L = accumarray([1:numel(K); K]', ones(numel(K), 1))
  댓글 수: 1
John D'Errico
John D'Errico 2015년 1월 22일
Those would have been my solutions, preferring either sparse or accumarray, depending on whether the result is desired to be full or sparse in the end.

댓글을 달려면 로그인하십시오.


John D'Errico
John D'Errico 2015년 1월 22일
Time to learn how to use sparse.
Or, if you prefer to work with full matrices, learn to use accumarray.
Or, if those options are not to your liking, learn to use use subsindx. That will take slightly more effort though.

카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by