user3385093
user3385093

Reputation:

Matlab for loop trouble

I'm trying to understand for loops better in Matlab since for some reason they don't work like other languages.

values = zeros(1,7);
for i =[1, 4, 10, 15, 22, 24, 36]
        variable = function(input, input, i);
        values(i) = function(input, variable);
end

So values becomes a 1x36 double where for i I get results, but any number that isn't i gets a column set to 0. Why does it still add columns for values I didn't choose for i?

Thanks

Upvotes: 0

Views: 45

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

You are preallocating values with 7 entries. When you assign a value at entry 10, entries 8 and 9 must be created too, and Matlab fills them with 0.

Here's an example:

>> clear
>> values = ones(1,7) % preallocate with ones
values =
     1     1     1     1     1     1     1
>> values(4) = 40
values =
     1     1     1    40     1     1     1
>> values(10) = 100 % the array will have to grow
values =
     1     1     1    40     1     1     1    0     0   100

Note also that having an array growing is not desirable, as it negatively impacts speed. It's better to preallocate to the final size, whenever it is known in advance.


Thanks to @Steve for the edit

If you want the results to be stored in consecutive entries, consider using a counting variable, e.g. k for your indexing which increases by 1 each step of the loop.

values = zeros(1,7);
% k stores the number of steps of the loop
k = 0;
for i =[1, 4, 10, 15, 22, 24, 36]
        % increment k
        k = k+1;
        variable = function(input, input, i);
        values(k) = function(input, variable);
end

Upvotes: 1

Related Questions