Linear Problem Matrix without For Loop
古いコメントを表示
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
2015 年 1 月 22 日
The number of columns is the max of K not the size of unique(K)
採用された回答
その他の回答 (2 件)
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
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
2015 年 1 月 22 日
0 投票
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.
カテゴリ
ヘルプ センター および File Exchange で Sparse Matrices についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!