What is the shortest way to write this in matlab?

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 these. What would be the β€œMatlab method” for writing this kind of thing, except for a simple index cycle and testing lam1 values?

+3
source share
2 answers

Something like that:

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 have a bunch, the Matlab path must write a function to execute them.

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

EDIT: for extra astringency you can 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 left 1 in the first part, the second part starts with 1.1

+2
source

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

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

lam , lessThanOne. , , lam, , ( ).

+5

Source: https://habr.com/ru/post/1739607/


All Articles