How do I use a vector as a set of indices?

3 ビュー (過去 30 日間)
Pratik Samant
Pratik Samant 2020 年 2 月 3 日
回答済み: Alex Mcaulley 2020 年 2 月 3 日
So, I have a 5000x1 vector y, the entries of y are all integer values between 1 and 10.
I want to create a new matrix, yrec, that is 10x5000, such that if y(1)=10 then yrec(10,1)=1, if y(2)=8 then yrec(8,2)=1, if y(3)=4 then yrec(4,3)=1 etc.
and all other entries in that row are equal to zero. I can do this through a for loop quite easily as follows
m=5000;
num_labels=10;
yrec=zeros(num_labels,m); %recoded y
for i=1:m
yrec(y(i),i)=1;
end
which works without issue. However, I was wondering if there is a vectorized way to do this? hopefully more computationally efficient than a for loop?
I tried
yrec(y,1:m)=1;
but this just sets every entry in yrec equal to 1 for some reason.

採用された回答

Alex Mcaulley
Alex Mcaulley 2020 年 2 月 3 日
Try this:
m = 5000;
num_labels = 10;
y = randi(num_labels,m,1);
yrec = zeros(num_labels,m);
yrec(sub2ind(size(yrec),y',1:m)) = 1;

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by