FIND command returns empty matrix using ==
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(3 个)
Guillaume
2017-12-1
编辑:Guillaume
2017-12-1
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 个评论
Jos (10584)
2017-12-1
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 个评论
Guillaume
2017-12-1
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
2017-12-3
编辑:Stephen23
2017-12-3
"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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!