First, what are you actually doing with M, Xdot1, etc.? Currently, the code overwrites them each N_m loop, without doing anything with the results
Try this: define sampled vectors, so you can later vectorize things:
index=randi([100,499],1,N_m);
x1_samp0 = x1(index);
x1_samp1 = x1(index+1);
...
Xdot1=(x1_samp1-x1_samp0)/dt;
...
M(:,1)=1;
M(:,2)=x1_samp0;
...
M(:,6)=x1_samp0.^2;
edit: changed my mind on other option; don't do it. Here are some general tips, though:
- if you have a set of conditions that can be expressed as variable=first, variable=second, etc. -- use a switch instead of if-elseif
- If you have a loop running over a set of conditions and operations which have nothing else in common -- just run each line individually, then fill in the "else" portion after
for j=1:N_basis
if j==1
M(i,j)=1;
elseif j==2
M(i,j)=x1(index(i));
elseif j==3
M(i,j)=y1(index(i));
end
end
does the same as the below, but cleaner and faster:
M(i,1)=1;
M(i,2)=x1(index(i));
M(i,3)=y1(index(i));
- many, many, many for loops can be replaced with vector operations. It's kinda the point of Matlab
Best Answer