简体   繁体   中英

Selecting elements from a matrix in matlab

I have a matrix which is 36 x 2, but I want to seperate the elements to give me 18, 2 x 2 matrices from top to bottom. Eg if I have a matrix:

1  2
3  4
5  6
7  8
9  10
11  12
13  14
...  ...

I want to split it into seperate matrices:

M1 = 1  2
     3  4

M2 = 5  6
     7  8

M3 = 9  10
     11 12   

..etc.

maybe the following sample code could useful:

a=rand(36,2);
b=reshape(a,2,2,18)

then with the 3rd index of b you can access your 18 2x2 matrices, eg. b(:,:,2) gives the second 2x2 matrix.

I think that the direct answer to your question is:

sampledata = [...
    0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10 0.11 0.12 0.13 0.14 0.15 0.16 0.17 0.18 1.01 1.02 1.03 1.04 1.05 1.06 1.07 1.08 1.09 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.17 1.18; ... 
    0.19 0.20 0.21 0.22 0.23 0.24 0.25 0.26 0.27 0.28 0.29 0.30 0.31 0.32 0.33 0.34 0.35 0.36 1.19 1.20 1.21 1.22 1.23 1.24 1.25 1.26 1.27 1.28 1.29 1.30 1.31 1.32 1.33 1.34 1.35 1.36];

for ix = 1:(size(sampledata,2)/2)
    assignin('base',['M' sprintf('%02d',ix)], sampledata(:,ix*2+[-1 0]))
end

This creates 18 variables, named 'M01' through 'M18', with pieces of the sampledata matrix.


However, please don't use dynamic variable names like this. It will complicate every other piece of code that it touches. Use a cell array, a 3D array (as suggested by @Johannes_Endres +1 BTW), or structure. Anything that removes the need for you to write something like this later on:

%PLEASE DO NOT USE THIS
%ALSO DO NOT BACK YOURSELF INTO A CORNER WHERE YOU HAVE TO DO IT IN THE FUTURE
varNames = who('M*');
for ix = 1:length(varNames )
    str = ['result(' num2str(ix) ') = some_function(' varNames {ix} ');'];
    eval(str);
end

I've seen code like this, and it is slow and extremely cumbersome to maintain, not to mention the headache and pain to your internal beauty-meter.

x = reshape(1:36*2,[2 36])'

k = 1
for i = 1:2:35
    eval(sprintf('M%d = x(%d:%d,:);',k,i,i+1));
    k = k+1;
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM