Unlike Python, C, C++ and other programming languages, Matlab starts the matrix index with 1 instead of 0. So just change the first number then it should be working without having error. N=40 a=0.9 x =zeros(41,41) for k=1:N for col = 1:40 for row = 1:40 x(row,col)=a.^(k+k)*1; end end end However, 1st to 39th iteration of k for loop might be overwritten and x would only show the result of 40th iteration of k for loop... And the final result of x would only be a 40-by-40 matrix filled with the value of 0.9^80=2.1847e-4 for all elements... Which could be simplifed as N=40 a=0.9 x=a^(2*N)*ones(N) Answer from Akihumi on mathworks.com
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 328880-how-many-for-loops-would-be-needed-to-loop-through-each-value-of-two-dimensional-array
how many for loops would be needed to loop through each value of two dimensional array - MATLAB Answers - MATLAB Central
March 9, 2017 - https://www.mathworks.com/matlabcentral/answers/328880-how-many-for-loops-would-be-needed-to-loop-through-each-value-of-two-dimensional-array#answer_257952 ... Only one, if you use linear indexing. However, the more typical answer would be "one ...
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 321975-using-nested-for-loop-with-2d-array
using nested for loop with 2D array - MATLAB Answers - MATLAB Central
January 26, 2017 - I have values for w(omega), phi(phase shift), and k(amplitude) stored in 3 separate 2D arrays. Each array is 131 row x 15 columns. To create a cosine I start at (1,1) in each array and plug those values into the formula for a cosine. Then I take that cosine I just created and add it to the cosine created from (1,2), then (1,3) and so on until I have summed the cosines from all 15 columns in that row.
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 116994-how-to-traverse-a-multidimensional-array
how to traverse a multidimensional array - MATLAB Answers - MATLAB Central
February 20, 2014 - % build cell array with only iith dimension having values, everything else ':' traverse = repmat({':'},1,nd); for kk = 1:sz(ii) % loop over the iith dimension ยท traverse{ii} = kk; do_something_with(Z(traverse{:})) end ยท end ยท Sign in to comment. David Young on 20 Feb 2014 ยท Open in MATLAB Online ยท
Top answer
1 of 8
95

You can use linear indexing to access each element.

for idx = 1:numel(array)
    element = array(idx)
    ....
end

This is useful if you don't need to know what i,j,k, you are at. However, if you don't need to know what index you are at, you are probably better off using arrayfun()

2 of 8
36

The idea of a linear index for arrays in matlab is an important one. An array in MATLAB is really just a vector of elements, strung out in memory. MATLAB allows you to use either a row and column index, or a single linear index. For example,

A = magic(3)
A =
     8     1     6
     3     5     7
     4     9     2

A(2,3)
ans =
     7

A(8)
ans =
     7

We can see the order the elements are stored in memory by unrolling the array into a vector.

A(:)
ans =
     8
     3
     4
     1
     5
     9
     6
     7
     2

As you can see, the 8th element is the number 7. In fact, the function find returns its results as a linear index.

find(A>6)
ans =
     1
     6
     8

The result is, we can access each element in turn of a general n-d array using a single loop. For example, if we wanted to square the elements of A (yes, I know there are better ways to do this), one might do this:

B = zeros(size(A));
for i = 1:numel(A)
  B(i) = A(i).^2;
end

B
B =
    64     1    36
     9    25    49
    16    81     4

There are many circumstances where the linear index is more useful. Conversion between the linear index and two (or higher) dimensional subscripts is accomplished with the sub2ind and ind2sub functions.

The linear index applies in general to any array in matlab. So you can use it on structures, cell arrays, etc. The only problem with the linear index is when they get too large. MATLAB uses a 32 bit integer to store these indexes. So if your array has more then a total of 2^32 elements in it, the linear index will fail. It is really only an issue if you use sparse matrices often, when occasionally this will cause a problem. (Though I don't use a 64 bit MATLAB release, I believe that problem has been resolved for those lucky individuals who do.)

๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 490519-using-a-for-loop-to-put-a-number-of-2d-arrays-in-a-directory-into-a-single-3d-array
Using a for loop to put a number of 2D arrays in a directory into a single 3D array - MATLAB Answers - MATLAB Central
November 11, 2019 - Hi, I have a number of 2D arrays (image files) in a directory which I am trying to open sequentially in a for loop so I can window them down, and then put them all into a 3D array. I know this is...
Find elsewhere
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 524719-accessing-elements-from-2d-array-using-for-loop
Accessing elements from 2d array using for loop - MATLAB Answers - MATLAB Central
May 11, 2020 - Accessing elements from 2d array using for loop. Learn more about image processing, for loop, if statement, digital image processing MATLAB and Simulink Student Suite
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 490514-nested-for-loop-for-2d-matrix
Nested For Loop for 2D Matrix - MATLAB Answers - MATLAB Central
November 11, 2019 - I have a data set which is 2D 600x1000 in dimensions. I have to create a nested for loop of the following format, ... which will go through the 1000 dim first taking the first 51x51 elements (the first column should be col 1-51 in the first loop, the second iteration sould be 2-52, third 3-53--as long as it reaches till the end).
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 1577145-how-to-store-2d-arrays-in-a-for-loop-inside-a-parfor-loop
How to store 2D arrays in a for loop inside a parfor loop? - MATLAB Answers - MATLAB Central
November 4, 2021 - I think you can do this simply by essentially "reshaping" the problem to satisfy the parfor requirement that the index expression uses the loop index in a sliced manner. (Unfortunately, parfor isn't smart enough to be able to prove that your code doesn't perform illegal indexing, and so you must work around). Some extra tweaking is required to get A in the original form. (Also, I adjusted your original indexing expression, it wasn't quite right) ... https://www.mathworks.com/matlabcentral/answers/1577145-how-to-store-2d-arrays-in-a-for-loop-inside-a-parfor-loop#comment_1816235
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 481748-iterate-over-single-array-dimension
iterate over single array dimension - MATLAB Answers - MATLAB Central
September 23, 2019 - I have a list of vectors stored as a 2D array, and want to apply a function to each row or column in the list. Is there a general way to iterate over a single array dimension without a 'for' loop? ... https://www.mathworks.com/matlabcentral/answers/481748-iterate-over-single-array-dimension#comment_749409
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 112386-how-to-loop-through-matrix
how to loop through matrix? - MATLAB Answers - MATLAB Central
January 14, 2014 - I have a 184x32 matrix, I would like to write a loop to print out the first 8 rows then skip the next 8 rows. for example * A * B * C * D * E * F * G * H outcome should print A-H and ski...
Top answer
1 of 1
3
You can use linear indexing, if you want to operate on all elements: X = rand(2,3,4); Y = zeros(size(X)); for k = 1:numel(X) Y(k) = X(k) ^ 2; end Of course Y = X .^ 2 would be easier without a loop, but this is thought as demonstration only. If you want to operate on submatrices, you can move them to the first dimensions temporarily: X = rand(2,3,4,5,6); operateOn = [3,5]; % Operate on submatrix along 3rd and 5th dimension v = 1:ndims(X); XX = permute(X, [operateOn, setdiff(v, operateOn)]); sXX = size(XX); XX = reshape(XX, [sXX(1:2), prod(sXX(3:end)]); for k = 1:size(XX, 3) submatrix = XX(:, :, k); ... do what you want end Another example is using a cell vector for indexing. If you want a subarray with indexing the the last two dimensions - independent from knowing how many dimensions the input has: X = rand(2,3,4,5,6); n = ndims(X); index = cell(1, n); index(:) = {':'}; index{end-1} = 3; index{end} = 4; Y = X(index{:}); % Equivalent to: X(:, :, :, 3, 4) You can replace a bunch of nested loops by a single loop also using an index vector instead of scalar indices, see Answers: 333926-recursive-function-for-replacing-multiple-for-loops : X = rand(2,3,4,5,6); nv = ndims(X); v = ones(1, nv); vLim = size(X); ready = false; while ~ready % Do what you need with X and the index vector v ... % Update the index vector: ready = true; % Assume that the WHILE loop is ready for k = 1:nv v(k) = v(k) + 1; if v(k) <= vLim(k) ready = false; % No, WHILE loop is not ready now break; % v(k) increased successfully, leave "for k" loop end v(k) = 1; % Reset v(k), proceed to next k end end This is equivalent to the following without the need to know the number of dimensions before: for i1 = 1:size(X, 1) for i2 = 1:size(X, 2) for i3 = 1:size(X, 3) for i4 = 1:size(X, 4) for i5 = 1:size(X, 5) v = [i1, i2, i3, i4, i5]; % Do what you need with X and the index vector v ... end end end end end See an example: https://www.mathworks.com/matlabcentral/answers/447469-looping-through-a-matrix-of-unknown-dimensions
๐ŸŒ
MathWorks
mathworks.com โ€บ matlabcentral โ€บ answers โ€บ 154080-cell-array-as-input-for-loop
Cell array as input for loop - MATLAB Answers - MATLAB Central
September 8, 2014 - Cell array as input for loop. Learn more about cell arrays, strings, for loop, array, function