How to assign 'null values' to certain ranges of an equation based on a criteria?

조회 수: 56 (최근 30일)
Hi guys,
I have two equations. I want one of those (Eq2) to only have valid values when Eq1 is yielding positive values. For all the negative values of Eq1 for given x,y, I want Eq2 to give null or invalid values.
Here's the sample:
x=[-10:10];
y=[-10:10];
Eq1 = @(x,y) x - y;
Eq2 = @(x,y) x + y;
[X,Y] = meshgrid(x,y);
Z1 = Eq1(X,Y);
Z2 = Eq2(X,Y);
Basically: I want Eq2 to have values for only those x,y where Eq1 is >= 0. For all x,y where Eq1 is < 0, I want Eq2 to have invalid/null values. So that when I go to graph Eq2 or just pull values from it, it only does it for areas where Eq1 is >= 0.
Is this possible?
Thank you

채택된 답변

Stephen23
Stephen23 2015년 7월 13일
편집: Stephen23 2015년 7월 13일
The simplest solution is to use indexing, as per Guillaume's solution. But this requires the array of values to be defined first, which is not optimal for a function. If you really want this as a function, rather than a fixed matrix of values, then try this:
Eq1 = @(x,y) x - y;
Eq2 = @(x,y) x + y;
Eq3 = @(x,y) Eq2(x,y) + rem(0,Eq1(x,y)>=0);
which can be tested in the command window:
>> [X,Y] = meshgrid(-4:4,-4:4);
>> Eq1(X,Y)
ans =
0 1 2 3 4 5 6 7 8
-1 0 1 2 3 4 5 6 7
-2 -1 0 1 2 3 4 5 6
-3 -2 -1 0 1 2 3 4 5
-4 -3 -2 -1 0 1 2 3 4
-5 -4 -3 -2 -1 0 1 2 3
-6 -5 -4 -3 -2 -1 0 1 2
-7 -6 -5 -4 -3 -2 -1 0 1
-8 -7 -6 -5 -4 -3 -2 -1 0
>> Eq3(X,Y)
ans =
-8 -7 -6 -5 -4 -3 -2 -1 0
NaN -6 -5 -4 -3 -2 -1 0 1
NaN NaN -4 -3 -2 -1 0 1 2
NaN NaN NaN -2 -1 0 1 2 3
NaN NaN NaN NaN 0 1 2 3 4
NaN NaN NaN NaN NaN 2 3 4 5
NaN NaN NaN NaN NaN NaN 4 5 6
NaN NaN NaN NaN NaN NaN NaN 6 7
NaN NaN NaN NaN NaN NaN NaN NaN 8

추가 답변 (1개)

Guillaume
Guillaume 2015년 7월 13일
There's no concept of null values in matrices, but you have NaN (Not a Number) instead.
Z1 = Eq1(X, Y);
Z2 = Eq2(X, Y);
Z2(Z1 < 0) = NaN; %set values of Z2 where Z1 is < 0 to NaN.

카테고리

Help CenterFile Exchange에서 Numeric Solvers에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by