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

13 vues (au cours des 30 derniers jours)
Angus Keane
Angus Keane le 14 Août 2014
Commenté : Andrei Bobrov le 14 Août 2014
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

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 14 Août 2014
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 commentaires
Angus Keane
Angus Keane le 14 Août 2014
you bloody ripper!
ive spent all day on this!
any idea what it falls under so i can read more about it?
Andrei Bobrov
Andrei Bobrov le 14 Août 2014
Firstly, please read Getting Started with MATLAB from MATLAB - Documentation

Connectez-vous pour commenter.

Plus de réponses (1)

Björn
Björn le 14 Août 2014
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.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by