从m大小的列索引向量创建0和1的m x n矩阵 [英] Creating an m by n matrix of 0s and 1s from m-sized vector of column indexes
本文介绍了从m大小的列索引向量创建0和1的m x n矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 m 维向量,整数从1到 n .这些整数是 m×n 矩阵的列索引.
I have a m-dimensional vector of integers ranging from 1 to n. These integers are column indexes for m × n matrix.
我想创建一个0s和1s的 m×n 矩阵,其中在 m 行中,由指定的列中有一个1我向量中的第m 个值.
I want to create a m × n matrix of 0s and 1s, where in m-th row there's a 1 in the column that is specified by m-th value in my vector.
示例:
% my vector (3-dimensional, values from 1 to 4):
v = [4;
1;
2];
% corresponding 3 × 4 matrix
M = [0 0 0 1;
1 0 0 0;
0 1 0 0];
在没有for循环的情况下有可能吗?
Is this possible without a for-loop?
推荐答案
当然,这就是他们发明稀疏矩阵:
Of course, that's why they invented sparse matrices:
>> M = sparse(1:length(v),v,ones(length(v),1))
M =
(2,1) 1
(3,2) 1
(1,4) 1
,如果需要,可以将其转换为完整矩阵,其中完整:
which you can convert to a full matrix if you want with full:
>> full(M)
ans =
0 0 0 1
1 0 0 0
0 1 0 0
这篇关于从m大小的列索引向量创建0和1的m x n矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文