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

4 次查看(过去 30 天)
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

采纳的回答

Andrei Bobrov
Andrei Bobrov 2014-8-14
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);

更多回答(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.

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by