Learn How to Loop a Matrix in Matlab: Step-by-Step Guide

In summary, the code is trying to add up the values in the matrix, but it keeps repeating the same value.
  • #1
gfd43tg
Gold Member
950
50
Hello, this block of code was given on a previous exam

Code:
M = [1 3 -2; 7 -5 1];
temp = 0;
for k = M
    temp = temp + k(2)
end
temp

And we are supposed to give the final output of temp. I have no idea how one loops over a matrix, not even elements or anything. What the heck does k = M mean?

So I just do temp = 0+7 on the first iteration, but what happens on the next iteration? temp = 7 + 7?? I ran this code and got 3. Does the value of k(2) change or something?
 
Physics news on Phys.org
  • #2
Maylis said:
I have no idea how one loops over a matrix, not even elements or anything. What the heck does k = M mean?
Read the documentation! http://www.mathworks.co.uk/help/matlab/ref/for.html

Or if you prefer learning by doing, try something like
Code:
M = [1 3 -2; 7 -5 1];
for k = M
   disp('Start iteration, k =')
   disp(k)
end
 
  • #3
Okay, well I did a new example
Code:
 B = [1 2; 3 4];
EDU>> temp = 0;
EDU>> for k = B
for j = B
k
j
temp = temp + k'*j;
end
end

k =

     1
     3j =

     1
     3k =

     1
     3j =

     2
     4k =

     2
     4j =

     1
     3k =

     2
     4j =

     2
     4

EDU>> temp

temp =

    58
I see how the 2nd one iterated it's k's. It just went through columns of k. Why is it here that it goes through all the columns twice? I don't see the connection. My initial thought was that it would be [itex]\begin{pmatrix}1 & 3 \end{pmatrix} * \begin{pmatrix} 1 \\ 3 \end{pmatrix} = 10[/itex] on the first iteration, then [itex]\begin{pmatrix}2 & 4 \end{pmatrix} * \begin{pmatrix} 2 \\ 4 \end{pmatrix} = 20[/itex], hence the answer would be 30. Why is the code not changing k on the 2nd iteration? It is still ##\begin{pmatrix} 1 & 3 \end{pmatrix}##.

The documentation says

creates a column vector index from subsequent columns of array valArray on each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes for a maximum of n times, where n is the number of columns of valArray, given by numel(valArray, 1, :). The input valArray can be of any MATLAB data type, including a string, cell array, or struct.

So it should be at the 2nd column for the 2nd iteration of k, yet it is still on the first.
 
Last edited:
  • #4
Why do you loop with k and j at the same time in the second example? It just makes things more complicated.
 
  • #5
It was an old test problem, I am trying to prepare for the final exam.

You have a history of beef with my old test problems. It seems to me that the prof writes cryptic or confusing exam problems, I wouldn't be a bit surprised if it's on purpose
 
  • #6
Maylis said:
Why is the code not changing k on the 2nd iteration? It is still ##\begin{pmatrix} 1 & 3 \end{pmatrix}##.

When you have multiple loops, the inner loop(s) must complete before the outer loop advances.

In other words, each iteration of the outer loop runs against every single iteration of the inner loop.

For example,

Code:
for k=1:2
    for j = 1:10
        %stuff in loop
    end
end

In this example, k=1 first. Then the inner loop goes over every single value of j (from 1 to 10), while k is still 1. Once the inner loop finishes, the outer loop advances to k=2 and the inner loop runs a second time.

This means that when you have 2 (or more) loops, the total number of iterations is equal to the number of possible values in each loop, in this case (# values in outer loop) * (# values in inner loop). In the above example there are 20 iterations, with k = 1 for the first 10 and k=2 for the last 10, and with j varying between 1 to 10 twice.

Connecting this back to your example, you are running two for loops with 2x2 matrices. This means there are 4 iterations, with each value of k in the outer loop running against each possible value of j in the inner loop. It seems like you thought there would only be 2 iterations, so hopefully this explains why there are 4.
 
  • Like
Likes 1 person
  • #7
You mean all this time with a nested loops the indices are not changing simultaneously? Oh my..
 
  • #8
Hey Kreil, I ran into an interesting problem related to what you were saying. So that's nice if you have a definite number for the indices of the loop, but suppose I had a code

Code:
for i = 1:40
for j = i:40

Then how many iterations should I expect? The inner loop has dependency on the outer loop. I'm not sure how much I should multiply by? The outer loop is 40, but the inner loop is what? 40*? = number of iterations
 
Last edited:
  • #9
Why don't you write out by hand a few loops, starting with i = 1, figure out how many loops are done using the j counter, and increment i by one? Or, you can program a nested loop with a counting variable. Compare the two results.
 
  • #10
I did that and got 820. I was expecting 1600. I am looking at it now more closely with only 5 instead of 40, but it is complicated to put it as a math formula, because once i changes to 2, j only goes from 2:5. I probably would need an equation that would more easily determine it.

Edit: Well, I discovered the answer would be 40 + 39 + 38 + ...

I had to look up that the ##\sum\limits_{k=1}^n k = \frac{n(n+1)}{2}, ##, man I would have had to just add all the numbers in my calculator. Who knows, I might not have seen the pattern either on the real exam.
 
Last edited:
  • #11
Maylis said:
Who knows, I might not have seen the pattern either on the real exam.

Didn't you learn about arithmetic and geometric series in high school math?

If not, you will be in for a tough time analyzing the performance of algorithms, etc.
 

1. How do I create a matrix in Matlab?

To create a matrix in Matlab, you can use the zeros or ones function to create a matrix of all zeros or all ones, respectively. You can also use the rand function to create a matrix of random numbers. Alternatively, you can manually input the elements of the matrix using square brackets.

2. What is the purpose of looping a matrix in Matlab?

Looping a matrix in Matlab allows you to perform the same operation or set of operations on each element in the matrix. This can save time and effort compared to manually performing the operation on each individual element.

3. How do I loop through a matrix in Matlab?

To loop through a matrix in Matlab, you can use the for loop or the while loop. The for loop is typically used when you know the number of iterations beforehand, while the while loop is helpful when the number of iterations is unknown.

4. Can I use conditional statements while looping through a matrix in Matlab?

Yes, you can use conditional statements such as if, if-else, or switch within a loop to perform different operations based on certain conditions. This can be useful for more complex operations on the elements of a matrix.

5. Are there any other methods for looping through a matrix in Matlab?

Yes, you can also use vectorization, which is a method of performing operations on arrays without using explicit loops. This can be more efficient and faster than using loops, but it may not always be feasible depending on the complexity of the operations being performed.

Similar threads

  • MATLAB, Maple, Mathematica, LaTeX
Replies
4
Views
561
  • MATLAB, Maple, Mathematica, LaTeX
Replies
5
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
4
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
7
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
2
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
8
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
4
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
6
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
2
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
7
Views
2K
Back
Top