Find indices for the minimum positive values in a cell
조회 수: 16 (최근 30일)
이전 댓글 표시
Hi all
i am not able to find the indices for the minimum positive values inside a 2x7 cell. I would find the cell number (containing this minimum element) and its position inside the cell. For example in the first cell the minimum positive value have index [row,column]=[1,2].
This is my 2x7 cell:
C = {[5 0.0001;0 0.1],3,-2,2,3,[-0.1 5],[2 0.0001];[1 2],[0.0001 1],2,4,5,[1 -0.1],6};
Thank you for the help
Regards
댓글 수: 0
채택된 답변
Rik
2020년 6월 19일
You can always consider cellfun if you want to apply a function to every element of your cell. It might not be the fastest option though.
C = {[5 0.0001;0 0.1],3,-2,2,3,[-0.1 5],[2 0.0001];[1 2],[0.0001 1],2,4,5,[1 -0.1],6};
[rows,cols]=cellfun(@myfun,C);
function [row,col]=myfun(A)
A(A<0)=inf;%make sure it isn't the minimum
[~,idx]=min(A(:));
[row,col]=ind2sub(size(A),idx);
end
댓글 수: 9
Rik
2020년 6월 19일
If you mean closest to 0, why did you say only positive? And do you want the actual value itself, or the indices, as you originally described?
Since inside the function you're working with a local copy of the array, you can simply use the abs function to remove the sign.
function [row,col]=myfun(A)
A=abs(A);
[~,idx]=min(A(:));
[row,col]=ind2sub(size(A),idx);
end
Please stop changing the requirements. Note that you can run this function as normal:
[row,col]=myfun([-1 -0.1]);
Think long and hard about what it is you want. Only then can you hope to solve this.
추가 답변 (1개)
Suhas Maddi
2020년 6월 19일
편집: Suhas Maddi
2020년 6월 19일
Hii Elda,You can use a for loops to go through each element in the cell and find indexes of minimum values for each cell element using the min() function.For more information and detailed examples, You can refer to : https://www.mathworks.com/help/matlab/ref/min.html
%You want to find minimum element and it's index in first Cell element
%M is the minimum value and [x,y] is the index of the minimum value in the cell element.
[M,I]=min(min(C{1,1}));
[x,y]=find(C{1,1}==M)
%To do this for the whole cell,You can use for loops to iterate through each element.
You can also refer to this post : https://www.mathworks.com/matlabcentral/answers/100813-how-do-i-find-the-indices-of-the-maximum-or-minimum-value-of-my-matrix
I hope this helps you.
댓글 수: 3
Suhas Maddi
2020년 6월 19일
Hii Elda,Yes Kind of in the lines of what you have mentioned.If you want to store the indices of minimum elements for each cell element,You can use a vector or matrix or another cell array Hope this helps.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!