how many for loops would be needed to loop through each value of two dimensional array

13 views (last 30 days)
Given a two dimensional array, how many for loops would be
needed to loop through each value separately?
I am new to matlab and for loops and don't understand this question. I would appreciate your help, thank you.

Answers (2)

Walter Roberson
Walter Roberson on 9 Mar 2017
Only one, if you use linear indexing.
However, the more typical answer would be "one per dimension", so 2 for a 2D array.
For example,
for J = 1 : 3
for K = 1 : 4
Matrix(J,K) = 10*J+K;
end
end
And if you had a 3D array, then for example,
for J = 1 : 3
for K = 1 : 4
for L = 1 : 7
Matrix(J,K,L) = 100*J + 10*K + L;
end
end
end
which would be 3 for loops, one per dimension.

John BG
John BG on 9 Mar 2017
Edited: John BG on 10 Mar 2017
Greg
it depends on the processing you want to perform and the type of 2D matrix you have.
1.
If the indices are not to be taken into account, then it's faster to just pull all elements with
A(:)
2.
if you can apply exactly the same function to each element then
arrayfun(@fun,A)
where @fun is an anonymous function defined like
fun=@(x) op_definition(x)
3.
if you really need the indices, one option is using one for loop each matrix dimension, as pointed out by Walter.
Another option not requiring any loop yet being able to discern any index consist of generating the full pattern of indices, and then without any for loop at all, just read each element following the pattern, for processing, like this
A=randi([-10 10],5)
L=combinator(5,2,'p','r');
A(sub2ind(size(A),L(:,1)',L(:,2)'))
=
10 3 3 0 -6
-10 -6 0 -8 4
-9 -4 -9 -1 -9
2 5 10 3 -2
-2 0 10 6 -4
ans =
Columns 1 through 12
10 3 3 0 -6 -10 -6 0 -8 4 -9 -4
Columns 13 through 24
-9 -1 -9 2 5 10 3 -2 -2 0 10 6
Column 25
-4
combinator.m is a really useful and popular function not included in the factory set of functions, and it's freely available from MATLAB file exchange
4.
If the matrix as certain repetition or symmetry then you may be able to skip one for loop.
Greg, if you find this answer useful would you please be so kind to mark my answer as Accepted Answer?
To any other reader, please if you find this answer of any help solving your question,
please click on the thumbs-up vote link,
thanks in advance
John BG

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!