not use if statement in embedded function matlab

I not use if statement in embedded function matlab. This is error disply. How do you solve this problem? Thank you.
[Editorial note: the picture is too large to make it practical to show it in this message directly. Also, the picture loads slowly. -- Walter]

Answers (1)

Is "t" a vector? If it is, then you need to record using logical indexing.
For example,
theta = zeros(size(t));
idx = t < tb;
theta(idx) = a0 + a1 * t(idx) + a2 * t(idx).^2 + a3 * t(idx).^3;
Note also that even for scalars you cannot use
if a < b < c
as that will be evaluated as
if ((a<b) < c)
which will compare "a" to "b" giving a logical vector of results, and then that logical vector of 0's and 1's will be compared to c.
You need to instead code this kind of "if" statement as
if a < b & b < c
except of course you would want to turn it in to logical indexing instead of an "if" statement if you are working with vectors.

2 Comments

Thank you Walter Roberson.i do follow your.it is good result.but i have some problem.
if i do follow this is OK. No error
function [y,y1] = fcn(u,x1,x2,x3,x4)
a0=x1;
a1=0;
a2=3*(x2-x1)/x3^2;
a3=-2*(x2-x1)/x3^3;
t=u;
i=u<x4;
j=(x2-x4>u)&&(x4<u);
y1=4;
if (i)
y=a0+a1*t+a2*t^2+a3*t^3;
elseif(j)
y=a0+a1*t+a2*t^2+a3*t^3;
else
y=0;
end
but i used this.
function [y,y1] = fcn(u,x1,x2,x3,x4)
a0=x1;
a1=0;
a2=3*(x2-x1)/x3^2;
a3=-2*(x2-x1)/x3^3;
t=u;
i=u<x4;
j=(x2-x4>u)&&(x4<u);
if (i)
y=a0+a1*t+a2*t^2+a3*t^3;
y1=4;
elseif(j)
y=a0+a1*t+a2*t^2+a3*t^3;
else
y=0;
end
This program has error old problem.
I don't know this problem .
How to be solve problem?
In that code, you only assign a value to y1 in the "if (i)" case.
Your condition (x2-x4>u)&&(x4<u) looks odd. It could be right, but without comments it is not obvious why that combination of circumstances would be wanted.
You do not need to store the results of the comparisons in variables unless you are using vectors; the code you have would give an error if you are using vectors. It is usually best not to mix the two styles.

Sign in to comment.

Categories

Find more on Programming in Help Center and File Exchange

Asked:

on 29 Apr 2011

Community Treasure Hunt

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

Start Hunting!