anyone could help understand what happened in this code

1 view (last 30 days)
cvals = 1200:100:1600;
bvals = 5:5:20;
for cidx = 1 : length(cvals)
c = cvals(cidx);
for bidx = 1 : length(bvals)
b = bvals(bidx);
.... compute something
result{cidx}(bidx) = .... some scalar
end
end

Answers (1)

Walter Roberson
Walter Roberson on 23 Sep 2015
cvals = 1200:100:1600 assigns a row vector of values to c, namely 1200 1300 1400 1500 1600
bvals = 5:5:20 assigns a row vector of values to b, namely 5 10 15 20
for cidx = 1 : length(cvals) is a for loop over the variable cidx, with initial value 1 and maximum value length(cvals) . We see that cvals has 5 entries so this is the same as for cidx = 1 : 5 .
for loops iterate over the given range of values, assigning one value at a time to the variable, executing the loop up to the matching "end" statement, then updating the loop variable to the next value, running again, and so on. After the loop is finished, the loop variable will be left as the last value that it was assigned in the loop.
Inside the for loop, you pull out the element of cvals corresponding to the current index. So effectively you are looping over the content of cvals but you also know how many of them you have done so far. So you can index arrays by "how many" instead of indexing by a value that might not even be an integer.
Same analysis for bvals.
The only twist beyond that is storing the results into a cell array. You can read about those in the documentation.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!