Help With Conditonally variant Anonymous function.

1 回表示 (過去 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 Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by