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

3 ビュー (過去 30 日間)
Angus Keane
Angus Keane 2014 年 8 月 14 日
コメント済み: Andrei Bobrov 2014 年 8 月 14 日
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);
  2 件のコメント
Angus Keane
Angus Keane 2014 年 8 月 14 日
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 2014 年 8 月 14 日
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.

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by