11 views (last 30 days)

Show older comments

I need to find values of a piece wise linear function. I used nested if condition as shown in code. But for all values of t, it is executing only first "if else" loop, and giving always x1d(t)= 0.5 andx2d(t)= 0.5 as output values. Am not able to figure out the mistake. help me.

for t = 1:1:26

if 0<t<=4

x1d(t) = 0.5*t;

x2d(t) = 0.5*t;

elseif 4<t<=7

x1d(t) = 0.5*t;

x2d(t) = 3.33;

elseif 7<t<=10

x1d(t) = 0.5*t;

x2d(t) = 10/3 - 0.5*(t-40/3);

elseif 10<t<=26

x1d(t) = 0.5*t;

x2d(t) = 0;

end

end

Paulo Silva
on 11 Sep 2011

Derek O'Connor
on 11 Sep 2011

Boredom Forecast: Discussion of Syntax. High: (78/100)

First, get the preferred indentation by using "smart indent" in the Matlab Editor.

for t = 1:1:26

if 0<t<=4

x1d(t) = 0.5*t;

x2d(t) = 0.5*t;

elseif 4 < t && t <= 7.

x1d(t) = 0.5*t;

x2d(t) = 3.33;

elseif 7<t<=10

x1d(t) = 0.5*t;

x2d(t) = 10/3 - 0.5*(t-40/3);

elseif 10<t<=26

x1d(t) = 0.5*t;

x2d(t) = 0;

end

end

Second, as Paulo Silva points out, compound logical expressions, such as 4 < t <= 7 are not allowed in Matlab, Fortran, Pascal, ..., etc. Instead you have to write (for the convenience of the compiler-interpreter (writer)), 4 < t && t <= 7.

Count yourself lucky. In some languages you would have to write

if 4 < t && (t < 7 || t = 7) etc.

This logical expression would take an eagle-eyed programmer anywhere from 10 mins to a day to check for errors (precedence rules for && versus ||, etc.).

This is crazy. Any compiler-interpreter that rejects 4 < t <= 7 is doing so for purely lexical-syntactical convenience. This is not a code generation problem. Most 1st or 2nd-year computer science students could write a (character-by-character) program that would translate

4 < t <= 7 into 4 < t && t <= 7.

For me, the key to Matlab's success, and what attracted me, was the important syntactical innovation by Cleve Moler: a notation that made it easy to translate statements in Linear Algebra into a programming language. This is what IBM's Jim Backus tried to do with the FORTRAN (FORmula TRANslation) (56?) compiler. He succeeded, despite the sceptics, and Cleve Moler succeeded, despite the sceptics, to produce programming languages that are widely used in scientific computing.

So, in typical Irish fashion, I will answer your question with a question:

Why can't Matlab, etc., recognize the simple statement

if 4 < t <= 7

Derek O'Connor.

PS: Another question: why is it so difficult to write anything but plain text on this site?

Anybody for Stack Exchange?

PPS: Yes, yes: we know how to get rid of all the elseif's

Derek O'Connor
on 12 Sep 2011

@Walter, done. Should I remove my answer from here? I'm not sure of the etiquette on double posting.

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

Start Hunting!