用常数列向量替换矩阵中的特定列 [英] Replace specific columns in a matrix with a constant column vector
问题描述
对于神经网络,我想用如下矩阵表示列向量y = [1;2;3]
:
For neural networking, I would like to represent a column vector y = [1;2;3]
in a matrix like so:
y = [1 0 0;
0 1 0;
0 0 1]
我的向量y
非常大,因此硬编码不是一种选择.另外,我想避免使用for
-循环.
My vector y
is very large, and so hardcoding is not an option. Also, I would like to avoid using for
-loops.
我到目前为止所做的:
y1 =[y; zeros(1,length(y)) ;zeros(1,length(y))] % add two rows with zeros in orde to give y the right format
idx = find(y1(1,:) == 2); % find all the columns containing a 2
y1(:,idx(1):idx(end)) = y1(:,[0;1;0]); % this does not work because now I am comparing a matrix with a vector
我也尝试过:
y1( y1 == [2;0;0] )=[0;1;0]; % This of course does not work
有没有一种方法可以指定我要比较y1 == [2;0;0]
中的列,还是有另一种方法可以解决这个问题?
Is there a way to specify I want to compare columns in y1 == [2;0;0]
, or is there another way to solve this?
推荐答案
从您的问题的上下文中,您希望找到一个矩阵,其中每一列都是一个身份矢量.对于同一性矢量,此矩阵中的每一列都是非零矢量,其中在由y
的每个位置表示的矢量位置中设置1,否则设置为0.因此,假设我们有以下示例:
From the context of your question, you wish to find a matrix where each column is an identity vector. For an identity vector, each column in this matrix is a non-zero vector where 1 is set in the position of the vector denoted by each position of y
and 0 otherwise. Therefore, let's say we had the following example:
y = [1 5 4 3]
您将以y_out
作为最终矩阵,即:
You would have y_out
as the final matrix, which is:
y_out =
1 0 0 0
0 0 0 0
0 0 0 1
0 0 1 0
0 1 0 0
有几种方法可以做到这一点.最简单的方法是使用 eye
声明身份矩阵,然后让y
从此矩阵中选择所需的列,并将它们作为列放入最终矩阵中.如果y
具有所有唯一值,那么我们将简单地基于y
重新排列此身份矩阵的列.因此:
There are several ways to do this. The easiest one would be to declare the identity matrix with eye
, then let y
pick out those columns that you want from this matrix and place them as columns into your final matrix. If y
had all unique values, then we would simply be rearranging the columns of this identity matrix based on y
. As such:
y_out = eye(max(y));
y_out = y_out(:,y)
y_out =
1 0 0 0
0 0 0 0
0 0 0 1
0 0 1 0
0 1 0 0
另一种方法是声明 sparse
矩阵,其中每个行索引只是y
中的那些元素,每个列索引从1递增到与y
一样多的元素:
Another way would be to declare a sparse
matrix, where each row index is simply those elements from y
and each column index is increasing from 1 up to as many elements as we have y
:
y_out = sparse(y, 1:numel(y), 1, max(y), numel(y));
y_out = full(y_out)
y_out =
1 0 0 0
0 0 0 0
0 0 0 1
0 0 1 0
0 1 0 0
另一种方法是使用 sub2ind
查找将线性索引插入矩阵,然后访问这些元素并将其设置为1.因此:
One more way would be to use sub2ind
to find linear indices into your matrix, then access those elements and set them to 1. Therefore:
ind = sub2ind([max(y) numel(y)], y, 1:numel(y));
y_out = zeros(max(y), numel(y));
y_out(ind) = 1
y_out =
1 0 0 0
0 0 0 0
0 0 0 1
0 0 1 0
0 1 0 0
这篇关于用常数列向量替换矩阵中的特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!