Loop control statements FOR

2 Ansichten (letzte 30 Tage)
taufiq smile
taufiq smile am 27 Apr. 2015
Beantwortet: Walter Roberson am 3 Jan. 2016
I have a code from my book tutorial. What is differences between 2 models of my code
count = [1,2];

Antworten (1)

Walter Roberson
Walter Roberson am 3 Jan. 2016
size((count)') produces a vector value, which then gets used as the second endpoint for the colon operator. This will generate an warning message, because the startpoint, increment, and endpoint for the colon operator must all be scalars. The first value of the scalar will be used.
With count being [1,2], count' is [1;2] and size() of that would be [2 1]. After the warning, the first value of the scalar will be used, so 2 will be used. The result would be as if 1:1:2 had been coded, and more generally would be the same as 1:1:size(count,2) had been coded (except for the warning.)
1:length(count) is the same as 1:1:length(count) which is the same as 1:1:max(size(count)) . In the case of count being a row vector of length 2, max(size(count)) is 2, so the effect would be the same as if 1:1:2 had been coded.
For the given input, the two have the same effect (except for the warning.) However, if count had been a column vector of length 2 then size((count')) would be size() of a row vector, the first element of which would be 1, and after the warning the first element would be chosen, resulting in 1:1:1, whereas length() of the column vector would still be 2 even with the different orientation so 1:1:2 would still be implied for the length() version.
Using length() with a 2D array is risky if the array size can vary, as length() always takes the longest dimension. If you write length() with a 2D array expecting there to be more rows than columns but it turns out there are only a few rows, then length() might suddenly be referring to the number of columns when you were expecting the number of rows. It is therefore better practice to only use length() when you are certain that you have a vector, and to otherwise use the two-argument form of size to request a particular dimension, like size(TheArray,2) to select the second dimension.

Kategorien

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

Community Treasure Hunt

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

Start Hunting!

Translated by