Attempting a simple matrix value replacement. Could i get some help?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Angus Keane
am 14 Aug. 2014
Kommentiert: Andrei Bobrov
am 14 Aug. 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
0 Kommentare
Akzeptierte Antwort
Andrei Bobrov
am 14 Aug. 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);
Weitere Antworten (1)
Björn
am 14 Aug. 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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!