简体   繁体   中英

How to create a sub-matrix in MATLAB

I have this work which I have to do by creating a sub-matrix out of a given data set. I will explain it below.

Suppose, I have the data set as:

100  200  300  400  500  600
101  201  301  401  501  601
102  202  302  402  502  602

So, I want to create sub-matrices as follows:

For the first iteration ->

[[101  201  301  401  501]
[102  202  302  402  502]]

and

[[601]
[602]]

For the second iteration ->

[[100  200  300  400  500]
[102  202  302  402  502]]

and

[[600]
[602]]

And so on... The process will continue till the number of rows in the main/starting matrix.

In short, I want a LOO (leave one out) implementation of this data set, so that I can further work on it.

If you guys have any idea on how to do it, please share it. :)

Assuming A is the main matrix, a1 and a2 will be your first set of sub-matrices and b1 and b2 will be the second set of sub-matrices.

>> A=[100  200  300  400  500  600
    101  201  301  401  501  601
    102  202  302  402  502  602];
>> a1=A(2:3,1:5)

    a1 =

   101   201   301   401   501
   102   202   302   402   502

>> a2=A(2:3,6)

a2 =

   601
   602

>> b1=A(1:2,1:5)

b1 =

   100   200   300   400   500
   101   201   301   401   501

>> b2=A(1:2,6)

b2 =

   600
   601

A proper indexing is your friend here. For the given matrix:

X = [
   100  200  300  400  500  600
   101  201  301  401  501  601
   102  202  302  402  502  602
];

The first subsets are:

S1A = X(2:3,1:end-1);
S1B = X(2:3,end);

and the second subsets are:

S2A = X(1:3,1:end-1);
S2B = X(1:3,end);

Since you want to perform this for all the two-rows combinations of the matrix, the rows indexing patten can be generated with the nchoosek function as follows:

X_seq = 1:numel(x);
idx = nchoosek(X_seq,2);

Then, with an iteration (just to keep things simple... althrough in Matlab is always recommended to vectorize as many computations as possile), you can extract all the matches:

idx_len = size(idx,1);
res = cell(idx_len,2);

for i = 1:idx_len
    idx_curr = idx(i,:);
    res(i,:) = {X(idx_curr,1:end-1) X(idx_curr,end)};
end

If you have the stats and ML toolbox then you can use their built-in cross validation functions. See cvpartition or crossvalind

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