extracting smaller matrices from a larger matrix through loop

15 次查看(过去 30 天)
hi all i have lets say a 100*2 matrix, like x data and corresponding y data. i want to divide or partition this in to 10 parts, like one part= x1 y1... x10 y10 2nd part x11 y11...x20 y20.. and so on. ie., i want to partition this 100*2 matrix in to ten 10*2 matrices. how can i do that through a loop? because i want each of these partitions and save them separately for plotting and other purposes. i am a beginner in matlab scripting. please could you help me? thanks in advance johan mark

回答(3 个)

Star Strider
Star Strider 2015-1-29
This is not as efficient as I would like it to be, but it works:
M = [1:100; 501:600]'; % Created Data
M10 = reshape(M, [], 10, 2); % Reshape
M10 = permute(M10, [1 3 2]); % Shuffle Dimsnsions
Q3 = M10(:,:,1) % See First 10 Rows
Q4 = M10(:,:,2) % See Second 10 Rows
  3 个评论
Star Strider
Star Strider 2015-1-29
My pleasure.
The shuffling simply puts the desired (10x2) submatrices in the third dimension of the matrix, so you can address them specifically with the third index. (It was not possible to do that with the reshape function alone.) If your original data are (Nx2) as you described, and you want to put them in (10x2) submatrices, this code will work.
Specifically, the permute call keeps dimension #1 where it is, and swaps the relative positions of dimensions #2 and #3 to make addressing the submatrices a bit more intuitive. The ‘Q3’ and ‘Q4’ assignments (that are there for illustration purposes only and do not have to be part of your final code) show how to use this addressing scheme to access your submatrices easily.
The one caveat is that the row size (the ‘N’) of your matrix — however large it is — has to be an integral multiple of 10 or the reshape call will fail.
Star Strider
Star Strider 2015-1-29
The sincerest expression of appreciation here on MATLAB Answers is to Accept the Answer that most closely solves your problem.

请先登录,再进行评论。


Guillaume
Guillaume 2015-1-29
I would use mat2cell to split your 100*2 matrix into a cell array of 10*2 matrices, and iterate over the cells:
m = [(1:100)' (201:300)']; %example matrix
submheight = 10; %height of submatrices
%the code only works if submheight is a divisor of the number of rows of m
%so make sure that is true:
assert(mod(size(m, 1), submheight) == 0)
rowdist = ones(1, size(m) / submheight) * submheight;
c = cell2mat(m, rowdist); %split into submatrices
for submatrix = c %iterate over cells
submatrix = c{1}; %convert cell to matrix
%... do whatever you want with submatrix, e.g:
plot(submatrix(:, 1), submatrix(:, 2));
end

Andrei Bobrov
Andrei Bobrov 2015-1-29
out = zeros(10,2,100/10);
for ii = 1:size(out,3)
out(:,:,ii) = M(k(ii)-9:k(ii),:);
end

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by