用常量列向量替换矩阵中的特定列 [英] 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
-loops.
My vector y
is very large, and so hardcoding is not an option. Also, I would like to avoid using for
-loops.
到目前为止我做了什么:
What I did so far:
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屋!