Attempting a simple matrix value replacement. Could i get some help?

im trying to write a script that says basically plots circles, but for radius less than sqrt(2) it plots lines. it seems like a simple task; where the vale of z(i,j) doesnt meet a condition, replace it with the corresponding value y(i,j)
(eg if z(3,2) is < 2, then z(3,2)=y(3,2))
currently i have:
clear all
X = 0:0.1:4;
Y = 0:0.1:4;
[x,y]=meshgrid(X,Y);
i = 1 : length(X);
j = 1 : length(Y);
z(i,j) = x(i,j).^2+y(i,j).^2;
z(z(i,j)<2)=y(i,j); %ie for values in z that are <2, they will be replaced by the corresponding values from the matrix y
contour(X,Y,z,5);
grid on;
however the problem is that it always returns the error:
> In an assignment A(I) = B, the number of elements in B and I must be the same.
any help please? the mathworks link on arrays doesnt help me

 채택된 답변

X = 0:0.1:4;
Y = 0:0.1:4;
[x,y]=meshgrid(X,Y);
z = x.^2+y.^2;
t = z<2;
z(t)=y(t);
grid on;
contour(X,Y,z,5);

댓글 수: 2

you bloody ripper!
ive spent all day on this!
any idea what it falls under so i can read more about it?
Firstly, please read Getting Started with MATLAB from MATLAB - Documentation

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Björn
Björn 2014년 8월 14일
That code with a two for-loops would have worked. In my code below I have taken the first z-equation outside the for-loop because it's faster.
clear all
X = 0:0.1:4;
Y = 0:0.1:4;
[x,y]=meshgrid(X,Y);
z=x.^2+y.^2;
for i = 1 : length(X);
for j = 1 : length(Y);
z(z(i,j)<2)=y(i,j); %ie for values in z that are <2, they will be replaced by the corresponding values from the matrix y
end
end
contour(X,Y,z,5);
grid on;
I'm sure there is a better way (maybe with the function find(z<2)) than doing this replacement with a for-loop, but I couldn't figure it out right now.

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2014년 8월 14일

댓글:

2014년 8월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by