Problem with matrix indexing
4 views (last 30 days)
Show older comments
I'm having problems getting a linear index to return the results in the form that i want.
Suppose we have three matrices:
Matrix A: 100x81
Matrix B: 9x20
Index: 49x9
I want to multiply A with B, but only the parts that are referred by the index. If we have Matrix A indexed like so:
A(:, Index), we get a 100x441 result, which is partially what i want. The 441 result is basically all of the results from A in linear index sequence (9*49). What i want is for the 49 dimension to get concatenated vertically (4900x9) instead of horizontally (100x441), like so:
What it returns (100x441)
1 2 3 ... 441
... (100)
What i want it to return (4900x9)
1 2 3 ... 9
... (4900)
My solution so far was to use reshape to get the matrix in the form that i wish, which is concatenated across the columns instead of rows, like so:
X = reshape(A(:, Index), 100*49, 9) * B;
I then reshape X again to return it to the form i want:
X = reshape(X, 100, 49, 20);
The problem with this solution is that reshape takes some processing power, and i think that it's possible to manipulate the index in a way that returns the 4900x9 row directly, and that would be way more efficient. Is this possible?
In summary:
I want to multiply indexed A with B, and have it return a 100x49x20 result in the fastest way possible.
0 Comments
Accepted Answer
Jan
on 22 Apr 2021
The CPU time of the reshape command is very tiny, because it only checks if the number of elements is not changed and then it replaces the size vector. reshape does not modify or move the contents of the the array in the RAM, because it does not change the order of element.
If your code does, what you want, it is a very efficient solution:
X = reshape(A(:, Index), 100*49, 9) * B;
X = reshape(X, 100, 49, 20);
More Answers (1)
Hrishikesh Borate
on 19 Apr 2021
Hi,
It’s my understanding that you are trying to construct a matrix of size 4900x9 by extracting the values from matrix A using indices defined in Index matrix.
Following is the code for the same :-
A = rand(100,81);
Index = randi(size(A,2),49,9);
output = zeros(size(A,1)*size(Index,1),size(Index,2));
for i=1:size(Index,1)
output((i-1)*size(A,1)+1:i*size(A,1),:) = A(:,Index(i,:));
end
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!