If statement element-by-element for vector of arbitrary size

I need to emulate this VBA code in Matlab:
If M > 1 Then
PR_NS = (kp * M ^ 2 / (km * M ^ 2 + 2)) ^ e1 _
* (kp / (2 * k * M ^ 2 - km)) ^ e2
Else
PR_NS = 1
End If
Where M is a column vector of arbitrary (unknown) size and other items (kp, km, e1, e2) are scalers.
The intent is to return a column vector PR_NS of the same size as M. Depending on each value of M, each value of PR_NS may either be 1 or the value resulting from the equation.
I know this is a very basic question, but I am a newbie and have an urgent need to implement this. Thanks!

More Answers (1)

You could use a loop, but logical indexing is better:
PR_NS = ones(size(M));
M_in_range = M > 1;
PR_NS(M_in_range) = (kp .* M(M_in_range) .^ 2 ./ (km .* M(M_in_range) .^ 2 + 2)) .^ e1 .* (kp ./ (2 .* k .* M(M_in_range) .^ 2 - km)) .^ e2;

Categories

Find more on Just for fun in Help Center and File Exchange

Asked:

on 29 Nov 2013

Answered:

on 29 Nov 2013

Community Treasure Hunt

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

Start Hunting!