using IF and && together
Show older comments
hello I have this prog that I combine if and & in my first prog in the line of the if the expression before the && is correct but the expression after the && is wrong it should give me an error when j is equal to 6 at that time it will read(x(j+1) =x(7) and I d not have x(7) but it does not. however if I write in the line of the if, this statement
[ if x_new(i)<x(j+1)&&x_new(i)>x(j)]
it gives the error
why when I write x_new(i)<x(j+1) after the && it does not give me an error? ===========================================================================
clc
clear all
x=0:0.2:1;
y=[0 0.199 0.389 0.565 0.717 0.84];
x_new=[0.1 0.33];
for i=1:length(x_new)
for j=1:length(x)
if x_new(i)>x(j) && x_new(i)<x(j+1)
y_new(i)=(((y(j+1)-y(j))/(x(j+1)-x(j)))*(x_new(i)-x(j)))+y(j)
end
end
end
your help is appreciated thank you Zhina
Accepted Answer
More Answers (1)
Guillaume
on 4 Feb 2018
x=0:0.2:1;
y=[0 0.199 0.389 0.565 0.717 0.84];
x_new=[0.1 0.33];
y_new = interp1(x, y, x_new);
If you really wanted to do it yourself then you would not use a loop to scan x:
x=0:0.2:1;
y=[0 0.199 0.389 0.565 0.717 0.84];
x_new=[0.1 0.33];
y_new = zeros(size(x_new)); %always preallocate your output
for i = 1:numel(x_new)
j = find(x_new(i) > x(1:end-1) & x_new(i) < x(2:end)); %can't use && because working on vector
y_new(i) = (((y(j+1)-y(j))/(x(j+1)-x(j)))*(x_new(i)-x(j)))+y(j)
end
Note that I've left the comparisons as you wrote them. They would produce an incorrect result if x_new(i) is exactly equal to any of the x values.
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!