Reputation: 143
in following code I'm disappointed because I want to let matlab do what I able to do per hand. This code is actually working well, if I write it by hand for every step, which is of course absoulte silly:) But could anybody point out the mistake if I try to do it with loops as you see in commented part:( Thanks again, mgm
aim of code: ask matlab whether x(1)
clear;
x=[0 2 4 6 8 10];
y=[0 1.1 1.3 2 2.1 3.6 4.5 8.3 9];
z=zeros(9);
for j=1:length(y)
% for i=1:length(x)
% for k=1:length(y)
% if (x(i)<y(j))&&(y(j)<x(i+1))
% z(j,k)=(x(1)+x(2))./2;
% else
% z(j,k)=y(j);
%
% end
% end
% end
% end
if (x(1)<y(j))&&(y(j)<x(1+1))
z(j,1)=(x(1)+x(2))./2;
else
z(j,1)=y(j);
end
if (x(2)<y(j))&&(y(j)<x(2+1))
z(j,2)=(x(2)+x(3))./2;
else
z(j,2)=y(j);
end
if (x(3)<y(j))&&(y(j)<x(3+1))
z(j,3)=(x(3)+x(4))./2;
else
z(j,3)=y(j);
end
end
Upvotes: 0
Views: 131
Reputation: 16045
In the loop, you write z(j,k)
but in the code without loop, it looks like you are doing z(j,i)
also in the loopwyou write: (x(1)+x(2))
, without loop, it looks like (x(i)+x(1+i))
You should write:
for j=1:length(y)
for i=1:length(x)
if (x(i)<y(j))&&(y(j)<x(i+1))
z(j,i)=(x(i)+x(i+1))./2;
else
z(j,i)=y(j);
end
end
end
Upvotes: 1