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

  • Context: MATLAB 
  • Thread starter Thread starter gfd43tg
  • Start date Start date
  • Tags Tags
    Matlab Matrix
Click For Summary

Discussion Overview

The discussion revolves around understanding how to loop through matrices in MATLAB, specifically focusing on the behavior of nested loops and the implications of indexing within those loops. Participants explore examples of matrix operations and the resulting outputs, as well as the underlying mechanics of loop iterations.

Discussion Character

  • Exploratory
  • Technical explanation
  • Debate/contested
  • Homework-related

Main Points Raised

  • One participant expresses confusion about the meaning of "k = M" and how to loop over a matrix, questioning the behavior of the variable k during iterations.
  • Another participant suggests reading the documentation and provides an alternative example to illustrate how to iterate through matrix elements.
  • A participant shares a new example with a different matrix and discusses the output, questioning why the outer loop does not change k during the inner loop's iterations.
  • Concerns are raised about the complexity of using multiple loops simultaneously, with one participant questioning the necessity of looping with both k and j.
  • Clarification is provided regarding how nested loops function, explaining that the inner loop must complete all iterations before the outer loop advances.
  • One participant reflects on their misunderstanding of how indices change in nested loops, expressing surprise at the number of iterations involved.
  • A question is posed about the expected number of iterations when the inner loop depends on the outer loop's index, indicating uncertainty about calculating total iterations.
  • Another participant suggests writing out iterations by hand or programming a counting variable to better understand the loop behavior.
  • A participant shares their findings on the total number of iterations for a specific nested loop scenario, revealing the arithmetic series involved in the calculation.
  • Discussion touches on the importance of understanding arithmetic and geometric series for future algorithm analysis, with one participant noting potential challenges if they lack this knowledge.

Areas of Agreement / Disagreement

Participants express varying levels of understanding regarding nested loops and matrix indexing, with some confusion remaining about the behavior of loop variables. There is no consensus on the best approach to teaching or understanding these concepts, and multiple viewpoints on the complexity of the examples are present.

Contextual Notes

Some participants highlight the need for clarity in the documentation and examples provided in MATLAB, suggesting that the complexity of the problems may stem from the way they are presented in educational settings.

gfd43tg
Gold Member
Messages
949
Reaction score
48
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
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
 
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 \begin{pmatrix}1 & 3 \end{pmatrix} * \begin{pmatrix} 1 \\ 3 \end{pmatrix} = 10 on the first iteration, then \begin{pmatrix}2 & 4 \end{pmatrix} * \begin{pmatrix} 2 \\ 4 \end{pmatrix} = 20, 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:
Why do you loop with k and j at the same time in the second example? It just makes things more complicated.
 
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
 
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   Reactions: 1 person
You mean all this time with a nested loops the indices are not changing simultaneously? Oh my..
 
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:
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.
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 4 ·
Replies
4
Views
4K
Replies
0
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 8 ·
Replies
8
Views
3K
Replies
2
Views
3K