find reverses the dimension of rows and column output vectors when input is a vector
3 次查看(过去 30 天)
显示 更早的评论
Hi together,
I observed some behavior of the find function, where I am not sure if this is intended or simply a bug.
When calling find on an 2-Dimensional array (with both dimensions are greater than 1) the returned row and column indices by find are a Nx1 vectors. You can concatenate them to get a Nx2 matrix with the indices like in the following example:
arr = [1 0 0; 0 1 1];
[row, col] = find(arr); % both are a Nx1 vector
indices = [row, col]; % this breaks if arr is 1x2
If now my input array has only one row (i.e. it is a horizontal vector), find still returns rows and column indices, but this time those are 1xN vectors and concatenating them in the same way like above with
indices = [row, col]
will not end up with the intended result. In my case those arrays are tables, where there are cases where the table has multiple lines and also cases where it only has one. The indices are needed for formatting specific cells in this table and it takes the format Nx2.
Do I now really need to add a check in my code wether the input array has only one line and then transpose the row and column vectors returned by find?
if size(arr, 1) == 1
rows = rows';
cols = cols';
end
Thanks for your help
0 个评论
采纳的回答
dpb
2021-6-21
It has always behaved to return the shape of the input -- a row vector input returns a row vector output. That is expected behavior throughout MATLAB and it would break a lot of code to change it, so that "ain't agonna happen!".
So, "Yes, Virginia", you do need to test for orientation to catenate the outputs if want them as column vectors -- or write to force them to be without the logical test as
>> [row, col] = find(arr(:).')
row =
1 1 1
col =
1 4 6
>> indices=[row(:) col(:)]
indices =
1 1
1 4
1 6
>>
This forces them to be column vectors when catenate and while not necessary in case they already are, doesn't hurt anything and saves the logical test.
This becomes a natural MATLAB idiom with experience...
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!