Same procedure for different matrices
Show older comments
Hey there, I'm not good with writing loops and I guess I need one for my problem. I have a couple of matrices of different sizes that I would like to split into quadrants and then take the average of all non-zero elements for each quadrant which I am able to do with the following code:
B = A(1:(mod(end, 2)==1)*0.5+end/2, 1:(mod(end, 2)==1)*0.5+end/2);
C = A(1:(mod(end, 2)==1)*0.5+end/2, (mod(end, 2)==1)*0.5+end/2+ 1:end);
D = A(end/2+(mod(end, 2)==1)*0.5 + 1:end, 1:(mod(end, 2)==1)*0.5+end/2);
E = A(end/2+(mod(end, 2)==1)*0.5 + 1:end, end/2+(mod(end, 2)==1)*0.5+ 1:end);
avg_A(:,:) = [mean(B(B(:)>0)) mean(C(C(:)>0)); mean(D(D(:)>0)) mean(E(E(:)>0))];
where A is the first of many matrices. Now, my question is, whether I can apply that code to all my other matrices (A2,A3,A4,...) without copying this code and change all the "A"s to "A2"s and so on. In the end I would like to have a matrix of size 2x2xnumber of matrices.
Hope you have enough information and can help me with that.
3 Comments
Do NOT waste your time writing bad code that creates or acceses separate variables with numbered variable names: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended."
Just use indexing: simple, fast, efficient, neat, simple, easy to understand, much less buggy, easier to debug, etc, etc, etc.
https://www.mathworks.com/matlabcentral/answers/143-how-do-i-make-a-series-of-variables-a1-a2-a3-a10
etc, etc, etc.
"whether I can apply that code to all my other matrices (A2,A3,A4,...) without copying this code"
Yes, when you put all of those arrays into one ND-array or cell array, and then simply loop over it using indexing. Note that your code may also be best put into a function.
Felix Koenig
on 26 Jul 2017
Jan
on 26 Jul 2017
Use a cell array instead as a container for arrays of different size:
A = {rand(23, 25), rand(22,25)};
size(A{1})
size(A{2})
Answers (1)
Use a subfunction:
A = {rand(23, 25), rand(22,25)};
B = zeros([2, 2, numel(A)]);
for iA = 1:numel(A)
B(:, :, iA) = QuadrantMean(A{iA});
end
function M = QuadrantMean(A)
S = floor(size(A) / 2);
A11 = A(1:S(1), 1:S(2));
A12 = A(1:S(1), S(2)+1:end);
A21 = A(S(1)+1:end, 1:S(2));
A22 = A(S(1)+1:end, S(2)+1:end);
M = [mean(A11(A11 ~= 0)), mean(A12(A12 ~= 0)); ...
mean(A21(A21 ~= 0)), mean(A22(A22 ~= 0))];
end
Categories
Find more on Matrix Indexing 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!