MATLAB: Optimizing a simple code

code optimizaition

Hi People
I trying to optimize the following code and get ride of the for loop. What the code dose, is simple. It estimates the next column in a matrix based on the previous column values times a matrix.
clc
clear
close all
dt=0.01;
t=0:dt:10;
sls=zeros(2,numel(t));
M_c=[0 1;0 0];
M_c=M_c+[1 0;0 1]*1/dt;
V_s=[0;1];
for i=1:numel(t)-1
sls(:,i+1)=(M_c*sls(:,i)+V_s)*dt;
end
Any suggestion for a built-in function that would do the for loop part?

Best Answer

For your particular problem there is a way to avoid the for-loop using the colon operator, but I doubt if it is what you had in mind as a "built-in" function. Just do this:
n = numel(t);
s2 = 0:dt:(n-1)*dt;
sls = [s2.*(-dt:dt:(n-2)*dt);s2];
I tend to agree with John and Geoff that the advantage of avoiding for-loops has been greatly exaggerated among many users of matlab. It is often the very best way to accomplish a given task, and as John states, even if an advantage is gained, it is often not worth the extra programming effort to achieve.
Related Question