Why does my <= statement not work?

I'm running a simple loop that applies a less than or equal to inequality to a value. Unfortunately, it is overlooking this value and not working. Here is my code
% Initial Conditions
clearvars
close all
Ms=1.989E30;
m = logspace(-2, 2, 400);
% m = 1E2:100:1E4
% (m<0.08, m**-0.3, numpy.where(m < 0.5, 0.08**-0.3 * (m/0.08)**-1.3, 0.08**-0.3 * (0.5/0.08)**-1.3 * (m/0.5)**-2.3))
%% def chabrier03individual(m):
k = 0.158*exp(-(-log(0.08))^2/(2*0.69^2))
if m<=1
u = 0.158*(1./m)*exp(-(log(m)-log(0.08))^2/(2 * 0.69^2));
else
v = k*m;
end

1 Comment

The comprison works as documented. Note the if documentation states " An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
You provided if with a 1x400 logical vector as its condition, it contains no non-zero elements:
>> nnz(m<=1)
ans = 0
Based on this I would expect the else part to be executed, and this is indeed what occurs when i run your code.
Note that your vector m contains just one value repeated 400 times over:
>> unique(m)
ans = 100
It is not clear why you wanted to create that 1x400 vector in such an obfuscated way.
EDIT: the OP originally defined
m = logspace(2, 2, 400);
but has since edited the question and changed it to:
m = logspace(-2, 2, 400);
The relevance of reading the if documentation is unchanged.

Sign in to comment.

Answers (1)

Shekhar Vats
Shekhar Vats on 31 Jan 2020
Can you please say more about your issue ? It's working as expected for me.

7 Comments

Hi yes, I couldn't get the u value to print, It does not recognise that instruction.
"I couldn't get the u value to print,"
Because your if condition is not true, I see no reason to expect u to be defined.
HC98' "Answer" moved here:
Apologies, I made an error in my code, I've added the correct version here
U shoiuld be defined... the entire point of this function is to produce values for m less than 1.
"U shoiuld be defined."
No. Your non-scalar logical vector does not contain only non-zeros:
>> nnz(m<=1)
ans = 200
>> numel(m)
ans = 400
Read the if documenttion to understand why this is relevant.
Most likely using if is entirely the wrong approach anyway, and you should be using indexing.
All I need is a clue why it won't work. I'm trying to transcribe it in MATLAB having found a copy of the code in Python which reads:
def chabrier03individual(m):
k = 0.158 * exp(-(-log(0.08))**2/(2 * 0.69**2))
return numpy.where(m <= 1,\
0.158*(1./m) * exp(-(log(m)-log(0.08))**2/(2 * 0.69**2)),\
k*m**-2.3)
The equivalent to numpy's where is to use indexing:
x = ...;
y = ...;
idx = m<=1;
z = y;
z(idx) = x(idx)

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 31 Jan 2020

Edited:

on 31 Jan 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!