FIND command returns empty matrix using ==
18 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
My code is required to run with either default variable inputs or manual inputs. The problem line runs fine for the default variables but when x_rip and y_rip are manually inputted, the last line shown below returns a '0×1 empty double column vector'. I have shown the relevant sections of code below. I haven't shown how the variables are manually inputted but the manual inputs of x_rip and y_rip are the same size matrix as the default input.
tramp_x = 4000;
tramp_y = 2000;
x=0:dx:tramp_x;
y=0:dy:tramp_y;
[x_arr, y_arr] = meshgrid(x, y);
%default inputs
x_rip = [1500, 1500];
y_rip = [500, 800];
for i = (1:2)
fixed_rip{i} = find(x_arr == x_rip(i) & y_arr == y_rip(i));
end
From reading previous posts, I understand that you can't use == in a find function for values that aren't exactly equal but I don't know how to solve this otherwise in my code. Please help!
1 Kommentar
Antworten (3)
Guillaume
am 1 Dez. 2017
Bearbeitet: Guillaume
am 1 Dez. 2017
You can indeed use find with a tolerance comparison as per Jos' answer. This is the most straightforward way to modify your code. You will have to judge what is an acceptable tolerance depending on the magnitude of your values.
fixed_rip{i} = find(abs(x_arr-x_rip(i)) <= x_tol & abs(y_arr-y_rip(i)) <= y_tol);
Or you could use ismembertol which can work the tolerance for you and will also avoid the for loop entirely:
[~, fixed_rip] = ismembertol([x_rip(:), y_rip(:)], [x_arr(:), y_arr(:)], 'ByRows', true, 'OutputAllIndices', true);
You can override the default tolerance used by ismembertol with the tol and 'DataScale' arguments if you so wish.
0 Kommentare
Jos (10584)
am 1 Dez. 2017
Replace A==B with abs(A-B)<Tol, where Tol is a value reflecting what difference between A and B should be considered equal. Example:
A = 1/3
B = 0.333
A==B
abs(A-B) < 0.001
4 Kommentare
Guillaume
am 1 Dez. 2017
I have tried but it isn't working
is a very useless statement if you don't tell us what you have tried.
It will work if you do it correctly. You obviously haven't done it correctly.
Stephen23
am 3 Dez. 2017
Bearbeitet: Stephen23
am 3 Dez. 2017
"My problem is that I only require 1 value that best approximates where x_arr = x_rip."
As the others have pointed out, using the equality operator is not robust. But to return just one value use the absolute difference and min, e.g. (untested):
[~,idx] = min(abs(x_arr - x_rip(1)));
If you want the closest for both x and y then you need to define what this means. One common and easy interpretation would be the closest in Euclidean space:
[~,idx] = min((x_arr - x_rip(1)).^2 + (y_arr - y_rip(1)).^2);
0 Kommentare
Siehe auch
Kategorien
Mehr zu Operators and Elementary Operations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!