How to use a vector as indices for matrix?

89 views (last 30 days)
Hi,
Let's say I have a matrix NxM , and i have a vector 1xM. the contents of the vector indicates for every column in which row i should put the value '1'.
example - 5x5 matrix A all zeros, and vector V 1x5 = [3 1 1 5 4]. I want to get:
0 1 1 0 0
0 0 0 0 0
A = 1 0 0 0 0
0 0 0 0 1
0 0 0 1 0
How can I do that without using loops? (my matrix size is very large)
Thanks

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 1 Dec 2014
Edited: Azzi Abdelmalek on 1 Dec 2014
V= [3 1 1 5 4]
m=numel(V);
n=max(V)
idx=sub2ind([n m],V,1:m)
out=zeros(n,m)
out(idx)=1

More Answers (2)

Image Analyst
Image Analyst on 1 Dec 2014
Edited: Image Analyst on 1 Dec 2014
How large is large to you? And, a for loop is not always slow. Look at my code where I have a matrix of 100 thousand rows and 100 thousand columns. Is your matrix larger than that? The elapsed time was 0.071 seconds - only 71 milliseconds for a pretty big array. How fast do you need it to be?
A = zeros(100000, 'uint8');
[rows, columns] = size(A)
numel(A)
V = randi(rows, 1, columns);
tic;
for k = 1 : columns
A(V(k), k) = 1;
end
toc;
  3 Comments
Hagai
Hagai on 2 Dec 2014
Edited: Hagai on 2 Dec 2014
I have tested all three answers, indeed yours has better run time then Andrei's, but Azzi's solution is the fastest. I don't have memory issues at the moment, but thanks for the idea of logic matrix, I will use it for this is only preliminary algorithm.
As for how big the matrices are - about the same size as you have given.

Sign in to comment.


Andrei Bobrov
Andrei Bobrov on 1 Dec 2014
n = numel(V);
A = accumarray([V(:) (1:n)'],1,[max(V) n]);

Community Treasure Hunt

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

Start Hunting!

Translated by