Help With Conditonally variant Anonymous function.

조회 수: 2 (최근 30일)
Mark Dawson
Mark Dawson 2020년 11월 29일
답변: Steven Lord 2020년 11월 29일
Okay, this question is more abstract than specific, ergo, I'll be using more pseudocode and less specifics.
Say I have a very important variable:
B2 = +/- val;
And three arrays:
z1=[1:1:500];
z2=[501:1:1500];
z3=[1501:1:2000];
Which in turn exist in larger array z such that:
z=[z1 z2 z3];
The value of B2 is given by the general relationships:
B2(z1) = -val;
B2(z2) = +val;
B2(z3) = -val;
Now, im well aware ill need an if/else loop, but I must program this in an anonlymous function:
B2=@(X)(...)
I think the following solution is something similar to what I'd like:
B_2 = @(X)(if X<=z(500)&&X>=z(1500) B_2 = +val, else B_2 = -val)
Before some genius suggest an anonymous function is unecaserry, stupid, superflous etc etc etc, theres no ather way i can implement it. It HAS to be a anonymous function, I'm sorry.
If anyone could help I'd be really apprecative. I've been doing coursework all day, my brains quite fried, i think im like 90% of the way to a solution, im just being buggered by the execution. Hopfully i wake up with some assistance :)
Ty guys.
  댓글 수: 3
Mark Dawson
Mark Dawson 2020년 11월 29일
Shouldnt happen. Consider z (the overall array) to be:
z=[1:1:2000]
Mark Dawson
Mark Dawson 2020년 11월 29일
I eddted the original post. Hopefully should be clearer.

댓글을 달려면 로그인하십시오.

답변 (3개)

Mark Dawson
Mark Dawson 2020년 11월 29일
편집: Mark Dawson 2020년 11월 29일
Thanks once again for the help guy. As always, I solved it on my own. Would've been neater with an anonymous function through. Ah well. If anyone from the future cares:
function beta_2 = b_2(Z)
z = [0:(40000)/1999:40000];
if Z < z(501) && Z > z(1501)
beta_2 =6.8e-03;
else
beta_2 = -6.8e-03;
end
end

Walter Roberson
Walter Roberson 2020년 11월 29일
B_2 = @(z) ((z>=z(501)&z<=z(1500)) * 2 - 1) .* val
The logical test that is satisfied by the range will return true (1) in the middle range, and false (0) outside the range. 1 * 2 - 1 is 1, so a match (true) will become 1. 0*2 -1 is -1 so a non-match (false) will become -1 . That all is multiplied by val.

Steven Lord
Steven Lord 2020년 11월 29일
Let's say val is 2. So if Z is between 1 and 500 B2 should be -2, if it is between 501 and 1500 B2 should be 2, and if it is between 1501 and 2000 B2 should be -2. You're trying to discretize your data.
edges = [1, 500, 1500, 2000]
edges = 1×4
1 500 1500 2000
values = [-2, 2, -2]
randomZ = randi([1 2000], 10, 1);
B2 = @(x) discretize(x, edges, values);
B2vals = B2(randomZ);
results = table(randomZ, B2vals)
results = 10x2 table
randomZ B2vals _______ ______ 771 2 1590 -2 731 2 901 2 384 -2 222 -2 345 -2 1754 -2 1471 2 1153 2

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by