How can I retrieve those elements by their positions in a matrix?

1 次查看(过去 30 天)
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.

采纳的回答

Voss
Voss 2024-2-20
编辑:Voss 2024-2-20
See sub2ind.
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)
0.6391 10.0000 NaN 0.9365 10.0000 NaN 0.3843 11.0000 NaN 0.2368 11.0000 NaN 0.3258 11.0000 NaN 0.0274 11.0000 NaN 0.7392 11.0000 NaN 0.9402 11.0000 NaN 0.7814 12.0000 NaN 0.1833 11.0000 NaN 0.8160 11.0000 NaN 0.1769 12.0000 NaN 0.0458 12.0000 NaN 0.9581 12.0000 NaN 0.7264 12.0000 NaN 0.3357 12.0000 NaN 0.6752 12.0000 NaN 0.4542 13.0000 NaN 0.4814 NaN NaN 0.3889 NaN NaN 0.1000 NaN NaN 0.6832 NaN NaN 0.8584 NaN NaN 0.9527 NaN NaN 0.7586 NaN NaN 0.4239 NaN NaN 0.0273 NaN NaN 0.5349 NaN NaN 0.7205 NaN NaN 0.3750 NaN NaN 0.0198 NaN NaN 0.8870 NaN NaN 0.7809 NaN NaN 0.5049 NaN NaN 0.7746 NaN NaN 0.4865 NaN NaN 0.3366 NaN NaN 0.9597 NaN NaN 0.7985 NaN NaN
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])
row = 6×3
10 10 11 11 11 11 11 11 12 11 11 12 12 12 12 12 12 13
col = repmat([1 4 7],6,1)
col = 6×3
1 4 7 1 4 7 1 4 7 1 4 7 1 4 7 1 4 7
idx = sub2ind(size(M),row,col) % idx is linear index in M
idx = 6×3
10 49 89 11 50 89 11 50 90 11 50 90 12 51 90 12 51 91
M(1:6,[3 6 9]) = M(idx); % use idx to assign values to columns 3, 6, 9
disp(M);
0.6391 10.0000 0.5349 0.9365 10.0000 0.7205 0.3843 11.0000 0.7809 0.2368 11.0000 0.0198 0.3258 11.0000 0.8870 0.0274 11.0000 0.7809 0.7392 11.0000 0.0198 0.9402 11.0000 0.8870 0.7814 12.0000 0.4865 0.1833 11.0000 0.0198 0.8160 11.0000 0.8870 0.1769 12.0000 0.4865 0.0458 12.0000 0.5049 0.9581 12.0000 0.7746 0.7264 12.0000 0.4865 0.3357 12.0000 0.5049 0.6752 12.0000 0.7746 0.4542 13.0000 0.7985 0.4814 NaN NaN 0.3889 NaN NaN 0.1000 NaN NaN 0.6832 NaN NaN 0.8584 NaN NaN 0.9527 NaN NaN 0.7586 NaN NaN 0.4239 NaN NaN 0.0273 NaN NaN 0.5349 NaN NaN 0.7205 NaN NaN 0.3750 NaN NaN 0.0198 NaN NaN 0.8870 NaN NaN 0.7809 NaN NaN 0.5049 NaN NaN 0.7746 NaN NaN 0.4865 NaN NaN 0.3366 NaN NaN 0.9597 NaN NaN 0.7985 NaN NaN

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by