tags:

views:

85

answers:

2
lam1 = 0.0:0.1:4.0  
lam = 1.60*lam1-0.30*lam1^2 for 0<lam1<=1
lam = lam1+0.30 for 1<=lam1<=4

I have a bunch of those. What would be the 'matlab way' of writing that kinda stuff, short of simple looping by indexes and testing the values of lam1 ?

+2  A: 

Something like this:

lam1 = 0:0.1:4; %lam1 now has 41 elements 0, 0.1, 0.2, ..., 4.0

lam = lam1;  % just to create another array of the same size, could use zeros()

lam = 1.6*lam1-0.30*lam1.^2;  

% note, operating on all elements in both arrays, will overwrite wrong entries in lam next; more elegant (perhaps quicker too) would be to only operate on lam(1:11)

lam(12:end) = lam1(12:end)+0.3;

but if you've got a bunch of these the Matlab way is to write a function to do them.

Oh, and you have lam1==1 in both conditions, you ought to fix that.

EDIT: for extra terseness you could write:

lam = 1.6*(0:0.1:4)-0.3*(0:0.1:4).^2;
lam(12:end) = (1.1:0.1:4)+0.3;

In this version I've left 1 in the first part, second part begins at 1.1

High Performance Mark
Ugh, compared to that a loop with an IF testing of elements seems a lot easier to read, IMHO.
ldigas
Then I bet, @Idigas, you like my 2nd solution even less ! Generally I prefer the vector operations to loops and ifs in Matlab.
High Performance Mark
Actually, for some reason I like the 2nd version a lot ... clean and readable (to me, at least) ... thanks Mark !!
ldigas
+5  A: 

I think the cleanest (i.e. easiest to read and interpret) way to do this in MATLAB would be the following:

lam = 0:0.1:4;          %# Initial values
lessThanOne = lam < 1;  %# Logical index of values less than 1
lam(lessThanOne) = lam(lessThanOne).*...
                   (1.6-0.3.*lam(lessThanOne));  %# For values < 1
lam(~lessThanOne) = lam(~lessThanOne)+0.3;       %# For values >= 1

The above code creates a vector lam and modifies its entries using the logical index lessThanOne. This solution has the added benefit of working even if the initial values given to lam are, say, in descending order (or even unsorted).

gnovice
I agree. Except I'd write 'lessThanOneIdx' or something similar instead of 'index'.
Jonas
@Jonas: Agreed, and updated. ;)
gnovice
+1 for the effort, but I still like the above a little more. It's more similar to how I write stuff away from keyboard.
ldigas
this avoids "magic numbers" and that is a good thing.
MatlabDoug
@MatlabDoug - true. And it should be written that way, I agree. But sometimes I write stuff which I barely understand on paper, and then when writing code I want as little as possible extra lines ... I don't know ... 'tis strange, but that's how my mind works.
ldigas

related questions