How do I make a function provide a ordered list?

2 ビュー (過去 30 日間)
James Metz
James Metz 2020 年 4 月 5 日
編集済み: James Metz 2020 年 11 月 25 日
I need to create a function that outputs and ordered list based on the length of the input.
The input is a struct with field name countries that contains a char vector with the abbreviations of particular countries.
i.e. struct(1).countries = 'US GB CZ'
I am using a for loop to go through each struct and countries field to determine which one has the largest amount of countries. I used the strlength() fxn to compare the lengths of the "countries" vectors, but now I need a way to ouput it in an ordered list.
I did something along the lines of
function out_out = in(struct)
for ii = 1:length(struct)
if strlength(struct(ii).countries) >= strlength(struct(ii-1).countries)
out = [struct(ii).title out]
end
end
out_out = out(:)
end
How can I compile all inputs into one big output list with the struct with the most countries at the top and the struct with the fewest at the bottom. Some structs may have equal number of countries. I do not want to lose any of the structs, just re-order them based on how many countries are in them.
  4 件のコメント
Rik
Rik 2020 年 4 月 8 日
It is not just your own question. You posted it on a public forum, asking others for help. People spent time helping you. The least you can do is to leave your question as it was so others with a similar question can benefit from the solution as well.
Rena Berman
Rena Berman 2020 年 5 月 14 日
(Answers Dev) Restored edit

サインインしてコメントする。

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 4 月 5 日
No need to use a for loop.
myStruct(1).countries = 'ABCDEF';
myStruct(2).countries = 'ABCDEFGHI';
myStruct(3).countries = 'ABCDEFG';
myStruct(4).countries = 'ABCD';
[~,idx] = sort(strlength({myStruct.countries}), 'descend');
sortedStruct = myStruct(idx);
Result:
>> sortedStruct.countries
ans =
'ABCDEFGHI'
ans =
'ABCDEFG'
ans =
'ABCDEF'
ans =
'ABCD'
  2 件のコメント
Ameer Hamza
Ameer Hamza 2020 年 4 月 5 日
James, the function is correct. You need to call it like this so that the output value is stored in a variable
sortedStruct = movies_by_cou(movies)
Ameer Hamza
Ameer Hamza 2020 年 4 月 6 日
James, I think you have added that line inside the function. Let me clearify a bit.
You need to create a file movies_by_cou.m and save it in current folder. Then paste the following code in that file
function sortedStruct = movies_by_cou(movies)
[~, idx] = sort(strlength({movies.countries}), 'descend');
sortedStruct = movies(idx);
end
And then on command window run
sortedStruct = movies_by_cou(movies);
and then check the content of sortedStruct

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by