Help With Conditonally variant Anonymous function.
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (3 件)
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.
0 件のコメント
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]
values = [-2, 2, -2]
randomZ = randi([1 2000], 10, 1);
B2 = @(x) discretize(x, edges, values);
B2vals = B2(randomZ);
results = table(randomZ, B2vals)
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!