matlab: addressing of one index without sub2ind

2019-07-26 04:46发布

问题:

This is very closely related to this other question, but that question wanted to avoid sub2ind because of performance concerns. I am more concerned about the "unelegance" of using sub2ind.

Let's suppose I want to create another MxN matrix which is all zeros except for one entry in each column that I want to assign from the corresponding entry in a vector, and choice of row in each column is based on another vector. For example:

z = zeros(10,4);
rchoice = [3 1 8 7];
newvals = [123 456 789 10];
% ??? I would like to set z(3,1)=123, z(1,2)=456, z(8,3)=789, z(7,4)=10

I can use sub2ind to accomplish this (which I used in an answer to a closely related question):

z(sub2ind(size(z),rchoice,1:4)) = newvals

but is there another alternative? Seems like logical addressing could be used in some way but I'm stumped, because in order to set the elements of a logical matrix to 1, you're dealing with the same element positions as in the matrix you actually want to address.

回答1:

There's a much simpler way of doing it.

nCols=size(z,2);
z(rchoice,1:nCols)=diag(newvals);


回答2:

You can just add the number of rows in previous columns to rchoice to get the linear index directly.

nRows = size(z,1); %# in case you don't know this already
nCols2write = length(newvals);
z(rchoice+[0:nRows:(nRows*(nCols2write-1)]) = newvals;