Stuart’s MATLAB Videos

Watch and Learn

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the Original version of the page.

How to fix common indexing errors with for loops 6

Posted by Doug Hull,

This video shows how to fix common errors in MATLAB when indexing into a vector or matrix in a for loop.

6 CommentsOldest to Newest

Robbie replied on : 1 of 6
Is there anything wrong with using the following?
c = [];
for i = 1:0.5:10
c(end+1) = i*10;
matt fig replied on : 2 of 6
@Robbie, The code you suggest works, however it is extremely slow for larger problems when compared with constructing a pre-allocated array in a FOR loop. If you want to avoid explicit pre-allocation for some reason, you can often do something like this (which I call dynamic pre-allocation): cnt = 1801; for ii = 10:-.005:1 d(cnt) = ii*10; % d is fixed size after first pass. cnt = cnt - 1; end
Daniel Armyr replied on : 3 of 6
@doug: Your third case is pretty much what I do on a daily basis. However, I have found myself more comfortable with the following syntax:
inData = 1:0.5:10;
c = nan(size(inData));
for i = 1:length(inData)
   c(i) = inData(i)*10;
disp ( c );
I also took the liberty of preallocating memory for the sake of it.
Kamran replied on : 4 of 6
The output of second part of your code is not the same as the first one. The output of the firs part is from 10 to 100 but the output of the second is from 0 to 100. Thank you for your great videos.
Abbey replied on : 6 of 6
parfor ii = 1:1:2*nsim %jj = j(ii) %p is a temporary variable if ii > nsim p_par = pvals(2); kk = k(ii-nsim); else p_par = pvals(1); kk = k(end); end disp(ii) [MuTmpA,MuTmpB,VarTmpA,VarTmpB,CovTmpAB,Scatter_tmp] = ModelCalc(kk,s_1,s_2,N,T,q,p_par,f,n_plt,pop_sample, plt_step); MuA(:,ii) = MuTmpA; MuB(:,ii) = MuTmpB; VarA(:,ii) = VarTmpA; VarB(:,ii) = VarTmpB; CovAB(:,ii) = CovTmpAB; index1 = 2*ii-1; index2 = 2*ii; Scatter_final(:,index1:index2) = Scatter_tmp;