Is there a more robust way for the following problem:
d = 1+(20-1).*rand(365,5);
bthD = 1:5;
I = repmat(bthD',73,1);
for i = 1:length(d);
q(i) = d(i,I(i));
end
Here, I are the indices that indicate which column of the matrix are required. q is the outcome where we have each row with the corresponding column number as specified by I. Is there an alternative way to find q?
modified question:
I have data:
d = 1+(20-1).*rand(365,5);
I would like to find the value in each row corresponding to the indices in I:
I = floor(1+(5-1).*rand(365,1));
This can easily be achieved by using a for loop:
for i = 1:length(d);
q(i) = d(i,I(i));
end
However, I would like to find an alternative way i.e. one that does not involve loops.
Use linear indexing:
sub2ind converts row (
ii) and column (I(ii)) indices to linear indices, which you can use to grab all the desired elements at once.