Tony Chivers
Tony Chivers

Reputation: 191

For loop storing values in MATLAB

I have asked a similar question before, see,

Double for loop in MATLAB, storing the information

I am storing the results from a for loop but this time my for loop numbers do not increase by one each time.

%% 
for q = [25,50,100,250,500,5000]

ActualTable(:,q)=ActualValues;
end

As you will see this code runs but it has large portions of rows in the matrix ActualTable which only contain 0's I would just like the rows that contain non-zero. So it is saving every single row from 25 to 5000 and only inserting my values in the 25, 50, 100 etc rows with all other rows containing a zero.

Upvotes: 0

Views: 654

Answers (2)

Raha
Raha

Reputation: 202

I'm assuming with the way that you have displaye it that ActualValues is just 1 value each time. The problem with your code is that q has increments other than 1. The solution is to append the value at the end each time or to use a counter.

Append:

ActualTable = [];
for q = [25,50,100,250,500,5000]
ActualTable(end+1)=ActualValues;
end

Count:

ActualTable = [];
c = 1;
for q = [25,50,100,250,500,5000]
ActualTable(c)=ActualValues;
c = c+1;
end

Note that changing the length of the array each time is not good coding practice. If you know how many final values there are going to be, you should instantiate ActualTable with that length.

Upvotes: -1

Adriaan
Adriaan

Reputation: 18187

for q = [25,50,100,250,500,5000]
    ActualTable(:,q)=ActualValues;
end

This says that MATLAB should loop over q, where q has six possible values. If q=25, the inner call will store ActualValues in column q, which is, as just said, 25. So of course using this q array you get a N-by-5000 matrix, since the last column you attempt to store something in is 5000, and MATLAB does not do Swiss cheese in matrices.

Instead, loop over a monotonically increasing index:

for ii = 1:numel(q)
    ActualTable(ii,:) = ActualValues(q(ii),:); % You said rows, let's use rows then
end

This way you have just 6 rows, since numel(q)=6, and get the data based on the iith value of q out of ActualValues.

Upvotes: 4

Related Questions