フィルターのクリア

Replacing values in a matrix based on values in a column vector

1 回表示 (過去 30 日間)
Digaamber Dhamija
Digaamber Dhamija 2020 年 6 月 21 日
編集済み: Digaamber Dhamija 2020 年 6 月 22 日
I have a column vector (with dimensions m x 1) which contains values from 1 to 10.
I want to make a matrix yMat with dimension m x 10, such that, in corresponding rows of y and yMat, the value at the column of yMat corresponding to the value in y is equal to 1.
All other values in yMat should be 0.
For example, if
y = [2; 4; 1; 8]
then
yMat = [0 1 0 0 0 0 0 0 0 0; 0 0 0 1 0 0 0 0 0 0; 1 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 1 0 0]
The following code works, but is there any way to do this without using a for loop?
yMat = zeros(m, 10); % m is the number of rows in column vector y
for i = 1:m
yMat(i, y(i)) = 1;
end

採用された回答

Digaamber Dhamija
Digaamber Dhamija 2020 年 6 月 22 日
編集済み: Digaamber Dhamija 2020 年 6 月 22 日
Just in case anyone else has a similar problem, I found an even simpler solution.
y = [2; 4; 1; 8];
yMat = 1:10 == y;
which produces a logical array yMat.
You can get numeric values by doing:
yMat = double(1:10 == y);
producing
yMat =
0 1 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0

その他の回答 (1 件)

Mara
Mara 2020 年 6 月 21 日
I came up with this. But not sure if this the easiest way to do it.
yMat = zeros(length(y)*10, 1);
yMat((y-1)*length(y)+ (1:length(y))') =1;
yMat = reshape(yMat, length(y), []);
  2 件のコメント
Digaamber Dhamija
Digaamber Dhamija 2020 年 6 月 21 日
編集済み: Digaamber Dhamija 2020 年 6 月 21 日
The formula
(y-1)*length(y) + (1:length(y))'
seems to be doing something similar to calculating the linear indices for the original dimensions of yMat.
It would also have worked if you did this
yMat = zeros(length(y), 10);
yMat((y-1)*length(y) + (1:length(y))') = 1;
Mara
Mara 2020 年 6 月 21 日
True, it does not have to be a vector for the indexing to work. Thanks for the feedback! I did not see that you received another answer already, it seems to be more intuitive than this one, anyways.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by