开发者

What is the shortest way to write this in matlab?

lam1 = 0.0:0.1:4.0开发者_如何学Go  
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 ?


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).


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜