MATLAB: A problem with grammar

beginnerMATLAB

Here is a function I wrote, with N beeing a scalar (example 6) and x a vector (example [0;1;2;3;4;5]). Y1 gets input as 0 in the example and Y2 as (36-x^2)
function [ sort1 , sort2 ] = front(N,x)
Y1=input('frontière inférieure: ','s') ;
s1=vectorize(Y1);
Y2=input('frontière supérieure: ','s');
s2=vectorize(Y2);
sort1= ones(1,N+1);
for d=1:1:N;
b=x(d);
a=s1(b);
sort1(d)=a;
end
sort2= ones(1,N+1);
for d=1:1:N;
b=x(d);
a=s2(b);
sort2(d)=a;
end
end
My problem are the lines a=s1(b) and a=s2(b). My goal is to inject the values of the vector x one by one in the expressions s1 and s2, but: 1)I am not sure my semantics are correct? 2)How does this program reacts when it receives a scalar instead of an expression?
This is what I get when i run the program:
frontière inférieure: 0
frontière supérieure: 36-x^2
??? Attempted to access s1(0); index must be a positive integer
or logical.
Error in ==> front at 12
a=s1(b);

Best Answer

Not sure that I've fully understood your goal. From what I've got you may try to use the EVAL function to evaluate your string. This is not the most elegant approach but can be a starting point:
function [ sort1 ] = front(N,x)
Y1=input('frontière inférieure: ','s') ;
s1=vectorize(Y1);
if ~isnan(str2double(s1))
sort1 = repmat(eval(s1),1,N+1);
else
sort1 = eval(s1);
end
end
There's margin to improve the code:
Related Question