Use fprintf to display an array with multiple strings in alphabetical order?

26 Ansichten (letzte 30 Tage)
Let's say I have an array like so:
a = ['cats '; 'dogs '; 'birds']
and I want to use fprintf to display this in a sentence like: "birds, cats, and dogs are animals." I'm trying to:
1. Use fprintf to display this array in a sentence. Hopefully with the two commas and 'and' inserted. The command
fprintf('%s',a);
just runs the words together. Also, I'm wondering if there's a way to write this without knowing the size of the array a ahead of time? i.e. if, given a vector with an arbitrary number of strings of arbitrary length, I could use fprintf to display them in a sentence like so.
2. I want the output to be sorted alphabetically. I can't, using the documentation for the sort command, figure out how to get it to treat rows in the array like single objects, to be sorted alphabetically by the first letter alone. (Actually, by storing the contents of a in a cell—and it gets rid of the nasty spaces I have to include in a string array—but using fprintf to display cells seems to tougher.)
Thanks for any help you can give.

Antworten (1)

Walter Roberson
Walter Roberson am 6 Nov. 2012
a = {'cats', 'dogs', 'birds'};
as = sort(a);
fprintf('%s, ', as{1:end-1});
fprintf('and %s are animals.\n', as{end});

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by