Clear Filters
Clear Filters

How to save "for" loop outputs in cell array?

4 views (last 30 days)
I generated a code that gives all the 2x2 submatrices from a 10x7 matrix while keeping the order. I want to save each output (submatrix) as a matrix in a cell array to view it later. Here's my code:
Any help is appreciated!
clear
clc
matrix=rand(10,7)
[r, c]= size(matrix);
for s=1:r-1
for n=s+1:r-s
for j=1:c
for i=j+1:c
submatrix=matrix([s n],[j i])
end
end
end
end

Accepted Answer

Walter Roberson
Walter Roberson on 16 Feb 2023
matrix=rand(10,7)
matrix = 10×7
0.6318 0.0444 0.8269 0.0640 0.5899 0.3461 0.0173 0.2847 0.9609 0.5289 0.7458 0.2970 0.9897 0.3715 0.5628 0.4570 0.3468 0.2856 0.6580 0.6526 0.8978 0.0288 0.0271 0.0540 0.7092 0.2769 0.9067 0.6632 0.2362 0.1842 0.1355 0.2507 0.8704 0.9809 0.1556 0.8881 0.2483 0.9374 0.5056 0.3340 0.8535 0.9362 0.1724 0.3315 0.5370 0.7434 0.6314 0.9615 0.2852 0.8577 0.5271 0.5347 0.2187 0.0493 0.2417 0.7776 0.1535 0.7549 0.9788 0.8407 0.5979 0.6664 0.4310 0.5730 0.7781 0.1726 0.3665 0.3435 0.5795 0.9217
submatrix = {};
[r, c]= size(matrix);
for s=1:r-1
for n=s+1:r-s
for j=1:c
for i=j+1:c
submatrix{end+1}=matrix([s n],[j i]);
end
end
end
end
whos submatrix
Name Size Bytes Class Attributes submatrix 1x420 57120 cell
celldisp(submatrix(1:5))
ans{1} = 0.6318 0.0444 0.2847 0.9609 ans{2} = 0.6318 0.8269 0.2847 0.5289 ans{3} = 0.6318 0.0640 0.2847 0.7458 ans{4} = 0.6318 0.5899 0.2847 0.2970 ans{5} = 0.6318 0.3461 0.2847 0.9897
  3 Comments
Walter Roberson
Walter Roberson on 16 Feb 2023
Indexing at end+1 in an assignment is a common MATLAB idiom for appending data to the end of an array. end is a keyword in this context that converts to the index of the last element of the index. In the case of a single index being used (linear indexing) end converts to the number of elements currently in the array. So assigning to submatrix{end+1} is a more compact way of assigning to submatrix{numel(submatrix)+1} which is assigning to one past the current end of the array.
It saves having to write something like
submatrix = [submatrix, {matrix([s n],[j i])}];
Although the language model is such that assigning one past the end of an array "should" be the same as overwriting the variable with the output of explicitly creating an appended list like the above, it is not necessarily the same internally. The MATLAB memory allocation routines use fixed sized blocks for small arrays, and those fixed sized blocks might have room to extend the array in-place without allocating more memory, so for efficiency purposes assigning to {end+1} has the potential to be faster.
HN
HN on 16 Feb 2023
This makes sense! Thank you for the explanation.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!