Loop through a Cell Array

2 views (last 30 days)
Dan Lynn
Dan Lynn on 23 Oct 2015
Answered: Guillaume on 23 Oct 2015
I am having trouble in approaching this problem. I have a cell array with letters, regions, and scores.
'A' 'W' 10
'B' 'MW' 80
'C' 'NW' 62
'D' 'NW' 98
The regions are assigned distances.
'NE' - 200 miles
'SE' - 300 miles
'MW' - 500 miles
'NW' - 600 miles
'W' - 700 miles
It always takes the same amount of miles to get from any region to one specific region. If one is in the NW region and wanted to go to W region, it will take them 700 miles to get to W. Likewise, if one is in the NE region, it will still only take them 700 miles to get to W.
My goal is to rearrange the cell array with the following steps in mind: - I will compare the first 2 highest scores and see which of its respective regions has the shortest distance. In this case, D and B are the two highest, so I will compare their distances. I will want to travel to B first because going to region MW is 100 miles shorter than going to NW. - Afterwards, I will compare D with the next highest scored letter and repeat.
My output should look like this:
'B' 'MW' 80
'D' 'NW' 98
'C' 'NW' 62
'A' 'W' 10
How can I approach this with a for loop? And assign the given miles to the regions so I can start comparing?
note: If two comparisons contain the same region, I will put the higher scored letter first.

Accepted Answer

Guillaume
Guillaume on 23 Oct 2015
Your sorting is nearly a multi-column sort (for which you'd use sortrows) except for your first criteria (smallest distance of two highest scores). As a result you have to use a loop (I think, couldn't find a way without)
scores = {'A' 'W' 10
'B' 'MW' 80
'C' 'NW' 62
'D' 'NW' 98};
distances = {'NE' 200
'SE' 300
'MW' 500
'NW' 600
'W' 700};
%first find distance corresponding to each region
[~, loc] = ismember(scores(:, 2), distances(:, 1));
scoredist = [distances{loc, 2}];
%second, find score order:
[~, scoreorder] = sort([scores{:, 3}], 'descend');
%create destination cell array:
sortedscores = cell(size(scores));
%loop until only one score left to process
for destrow = 1:size(scores, 1)-1
%find shortest distance between the two highest score remaining
[~, shortidx] = min(scoredist(scoreorder([1 2]))); %shortidx is either 1 or 2
%copy the corresponding row in destination cell array
sortedscores(destrow, :) = scores(scoreorder(shortidx), :);
%remove processed score
scoreorder(shortidx) = [];
end
%add final left-over score
sortedscores(end, :) = scores(scoreorder, :)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!