How can I retrieve those elements by their positions in a matrix?
2 views (last 30 days)
Show older comments
I have a matrix example as shown above, and the data in column A, D, G share the same row index. In column B, E, H, there are specified row positions, and referred to the data in column A, D, G respectively. In column C, F, I, there are elements expected to be retrieved from the column A, D, G respectively according to the specified row positions.
0 Comments
Accepted Answer
Voss
on 20 Feb 2024
Edited: Voss
on 20 Feb 2024
For example, I'll use it to construct a matrix like the one you describe.
M = NaN(13,9);
M(:,[1 4 7]) = rand(13,3);
M(1:6,[2 5 8]) = [10 10 11; 11 11 11; 11 11 12; 11 11 12; 12 12 12; 12 12 13];
So far, columns 3, 6, and 9 (corresponding to columns C, F, and I in your data set) have not been populated (except for initializing with NaNs):
disp(M)
Now populate the first few rows of columns 3, 6 and 9 in M, using sub2ind along with row and column indices:
row = M(1:6,[2 5 8])
col = repmat([1 4 7],6,1)
idx = sub2ind(size(M),row,col) % idx is linear index in M
M(1:6,[3 6 9]) = M(idx); % use idx to assign values to columns 3, 6, 9
disp(M);
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices 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!