logical operations on particular matrix elements

2 views (last 30 days)
I have the following code:
numels = 7;
numpts = 3;
C = sparse(numpts,numels)
A = randi(numels,[numpts,1]);
B = rand(numpts,1);
I want to treat the matrix A as an index for the columns of matrix C and move the values of B to their respective columns.
So if we have:
A = [3;3;6];
B = [0.383;0.892;0.192];
Then we should be able to get:
full(C) =
0 0 0.383 0 0 0 0
0 0 0.892 0 0 0 0
0 0 0 0 0 0.192 0
I thought that
C(:,A)=B;
might work, but C(:,A) attempts refers to a matrix and not a set of values.
BTW, I want a logical operation, I don't want to use accumarray or something. It is important that it is fast.
Any help is appreciated.
  1 Comment
Christopher
Christopher on 9 Aug 2015
I've found that I can just find the indices in the sparse matrix and thus use the following:
newA = (A-1).*numpts+(1:numpts)';
C(newA)=B;
However, I've found that using larger matrices of C (required for my implementations), execution of C(newA)=B; is EXTREMELY SLOW.
How can I make this operation faster?

Sign in to comment.

Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 9 Aug 2015
Edited: Azzi Abdelmalek on 9 Aug 2015
numels = 7;
numpts = 3;
C = sparse(numpts,numels)
A = [3;3;6];
B = [0.383;0.892;0.192]
idx=sub2ind(size(C),1:numel(A),A')
C(idx)=B
full(C)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!