Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You seem to be on the right track, aside from the syntax errors. So a few comments:</p> <ul> <li><code>ISFIELD</code> returns true/false</li> <li>a better way to test the data type of variables is using is** family of functions: <code>ISNUMERIC</code>, <code>ISSTRUCT</code>, <code>ISCHAR</code>, ...</li> <li>you should read on the difference between <code>if</code>/<code>for</code>/... constructs</li> <li>the <code>SORT</code> function can handle both vector of numbers and cell array of strings. You should use that functionality (read the documentation page first)</li> <li>The syntax for accessing structure fields dynamically is: <code>structName.(dynamicExpression)</code> </li> </ul> <p>Having said that, here is how I would write such a function:</p> <pre><code>function structSorted = sortStruct(structArray, fname) if ~isfield(structArray,fname) error('Invalid Field Name') end if isnumeric( structArray(1).(fname) ) data = [structArray.(fname)]; else data = {structArray.(fname)}; end [~,order] = sort(data); structSorted = structArray(order); end </code></pre> <p>And lets test the function with some random array of structures:</p> <pre><code>%# lets build some array of structures chars = char(97:122); str = cellstr( chars(ceil(numel(chars).*rand(10,6))) ); [s(1:10).str] = str{:}; num = num2cell(rand(10,1)); [s(1:10).num] = num{:}; %# sort according to a field s_str = sortStruct(s, 'str'); s_num = sortStruct(s, 'num'); %#s_err = sortStruct(s, 'zzzzz'); %# compare the two sorted array of structures myS2C = @(s) squeeze(struct2cell(s))'; %'# a helper function to show results myS2C(s_str) myS2C(s_num) </code></pre> <p>Sorting by the field <code>str</code> gave:</p> <pre><code>&gt;&gt; myS2C(s_str) ans = 'cbawoj' [ 0.10401] 'fqwiek' [ 0.17567] 'fskvdc' [ 0.46847] 'hezhbh' [ 0.33585] 'kyeaxv' [ 0.67539] 'ooumrm' [ 0.20895] 'qbnqit' [ 0.90515] 'wcwyjs' [0.056705] 'wdyhlz' [ 0.52189] 'ytdoze' [ 0.91213] </code></pre> <p>while sorting by the field <code>num</code>:</p> <pre><code>&gt;&gt; myS2C(s_num) ans = 'wcwyjs' [0.056705] 'cbawoj' [ 0.10401] 'fqwiek' [ 0.17567] 'ooumrm' [ 0.20895] 'hezhbh' [ 0.33585] 'fskvdc' [ 0.46847] 'wdyhlz' [ 0.52189] 'kyeaxv' [ 0.67539] 'qbnqit' [ 0.90515] 'ytdoze' [ 0.91213] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload