Selecting elements of an array meeting certain criteria help

Associate
Joined
6 Nov 2006
Posts
722
Location
Devon
I'm trying to pick out elements of an array for plotting which fulfill a certain condition on another array to plot. I know that probably isn't too clear, so here's an example of how I'm doing it currently

Code:
j=1;
for i=1:221184
if(lat(i)>0)
qplot(j)=q(i) ;
psiplot(j)=psi(i) ;
j=j+1 ;
end
end
scatter(psiplot,qplot)

Now I remember reading somewhere that this wasn't the best practice way of doing it but I'm not sure what the best way of doing it is. If anyone can help I'd appreciate it as I'm trying to improve my programming skills and to do things the right way rather just whatever works which is how I currently do it. I'm sorry if this is a stupid/easy question.
 
Associate
OP
Joined
6 Nov 2006
Posts
722
Location
Devon
Thanks, that's the kind of thing I was after. I thought that using loops wasn't the most efficient way but was unsure how else to approach the problem. Thanks for the tip about using plot instead of scatter too.
 
Associate
OP
Joined
6 Nov 2006
Posts
722
Location
Devon
That's really interesting, thanks for taking the time to write that out. I think I kind of follow that. Are there any resources you'd recommend for trying to improve my matlab skills for things like this and understand more about how I should be doing things rather than just what happens to work like how I do it at the moment?
 
Associate
OP
Joined
6 Nov 2006
Posts
722
Location
Devon
A rule of thumb in Matlab, if you have for loop or an if statement then you are quite possibly doing something wrong. Make sure you know your linear algebra. If you use matlab correctly it will be much faster than your hand written c code.

Since making this thread I've been trying to write things more efficiently but I'm slightly unsure how I'd write the following without an if/else, which you suggest is probably the least efficient way to do it
Code:
for i=1:timestep+1
    if(x(i)<deltat)
        mheight(i) = 2000*0.5*(1-cos(pi*x(i)/deltat)) ;
    else
        mheight(i) = 2000 ;
    end
end

apologies if it's a really stupid question
 
Back
Top Bottom