I have to answer the following question: examine the following for statements and determine how many times each loop will be executed:
a) for ii=-32768:32767
b) for ii=32768:32767
c) for kk=2:4:3
d) for jj=ones(5,5)
so for a I did this:
for ii=-32768:32767
disp(ii);
end
and in the workspace I have the value of ii as 32767 so I was wondering if this is the number of times the loop is excecuted.
I also did it for he second one and got an empty array I am not sure what it means and for the third I got just 2 I also dont understand why.

 Akzeptierte Antwort

Roger Stafford
Roger Stafford am 3 Dez. 2014

1 Stimme

You shouldn't have to actually activate those 'for-loops' to determine how many times they will execute. You can do it in your head. The first one advances by one each step:, -32768, -32767, -32766, ..., 32767, so you just count the number of these integers, namely 32767 - (-32768) + 1 = ?. The second one is "none"; 32768 is already too far. The third one has 2 only since 2+4 would be beyond 3 and therefore it executes just once. The last one you can read about at:
http://www.mathworks.com/help/matlab/ref/for.html
"The loop executes a maximum of n times, where n is the number of columns of valArray, given by numel(valArray,1,:)."

4 Kommentare

Pam
Pam am 3 Dez. 2014
oh ok thank you and I did think of it tht way before but I was not sure and the last one does confuse me thank you for the link.
Pam
Pam am 3 Dez. 2014
so from reading the article, n times is the column number so in this case it would be once
Roger Stafford
Roger Stafford am 3 Dez. 2014
No, it would be five! 'ones(5,5)' creates a 5-by-5 array of ones so it must have five columns. Note that in that case 'jj' would be a column vector of five ones each time. Try doing it with ones(7,4). It should execute four times and each time 'jj' would be a column vector of seven ones.
Pam
Pam am 3 Dez. 2014
oh ok oops sorry I forgot it was 5 i dont know why I read 1 thank you!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

Pam
am 3 Dez. 2014

Kommentiert:

Pam
am 3 Dez. 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by