finding the coordinates of a value in a cell array

8 views (last 30 days)
for x = 1:100
for y = 1:61
b = abs(bsxfun(@minus,q{x,y},kevin))
averagesAcrossColumns = mean(b, 2);
b = abs(bsxfun(@minus,b,averagesAcrossColumns));
b = sum(b, 2);
s{x,y} = b;
end
end
q is a cell array that has has many matrices. kevin is a variable that is a 1x60 matrix.
I want to add an additional line to the code so that I find the smallest three values ie smallest three sums in variable s. The output should give me the position in the cell array, row and column number in the matrix. Also shortening the code to make it more cpu and memory effective would be appreciated.
thanks

Accepted Answer

Image Analyst
Image Analyst on 7 Dec 2014
There is no reason why S should be a cell array. The last two lines should simply be
s(x,y) = sum(b, 2);
Make it just a normal numerical array (double). Then try this:
sorted_s = sort(s(:), 'ascend');
% Find rows and columns where it's the min
% There may be more than one location, particularly if S is integer.
[rows1, columns1] = find(s == sorted_s(1))
% Now find the second and third smallest locations.
[rows2, columns2] = find(s == sorted_s(2))
[rows3, columns3] = find(s == sorted_s(3))
I really don't know what you're doing with bsxfun, q, kevin, and all that. I urge you to avoid cell arrays unless they're really necessary such as when you have collections of different length strings, or collections of variables where the type of the variable (char, integer, structure, etc.) varies on a element by element basis.
  3 Comments
Image Analyst
Image Analyst on 10 Dec 2014
Yes, that's why I said "I urge you to avoid cell arrays" - they're always more complicated.
AA
AA on 10 Dec 2014
s(x,y) = sum(b, 2); this command gives me an error. can you give me a solution with a cell array? thanks

Sign in to comment.

More Answers (1)

AA
AA on 11 Dec 2014
mn = cellfun(@(x) min(x(x>0)),q,'Un',0);
[mn,idx] = min(fliplr([mn{:}]));
mn % Show the minimum positve value.
idx = length(q) - idx + 1 % Which cell has the min.
L = cellfun(@(x) find(x==mn),q,'Un',0);
L = L{idx} % And the positions.

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!