Stuart’s MATLAB VideosWatch and Learn

This is machine translation

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 loops6

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.

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;
end

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;
end
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.
dhull replied on : 5 of 6
@Kamran, It is never claimed they have the same results. Doug
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;

This site uses Akismet to reduce spam. Learn how your comment data is processed.