<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
		>
<channel>
	<title>Comments on: Iterating over Non-Numeric Values</title>
	<atom:link href="http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/feed/" rel="self" type="application/rss+xml" />
	<link>http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/</link>
	<description>Loren Shure works on design of the MATLAB language at MathWorks. She writes here about once a week on MATLAB programming and related topics.</description>
	<lastBuildDate>Mon, 13 Feb 2012 13:24:10 +0000</lastBuildDate>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
	<item>
		<title>By: Thomas M</title>
		<link>http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-32506</link>
		<dc:creator>Thomas M</dc:creator>
		<pubDate>Wed, 21 Sep 2011 17:31:02 +0000</pubDate>
		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-32506</guid>
		<description>Is there any way to iterate over a Structure defined inside of an EML block in Simulink?  The fieldnames method needs the coder.extrinsic(&#039;fieldnames&#039;); declaration, but it still doesn&#039;t accept fn{n} because cell arguments are not acceptable in EML blocks.</description>
		<content:encoded><![CDATA[<p>Is there any way to iterate over a Structure defined inside of an EML block in Simulink?  The fieldnames method needs the coder.extrinsic(&#8216;fieldnames&#8217;); declaration, but it still doesn&#8217;t accept fn{n} because cell arguments are not acceptable in EML blocks.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Mike G</title>
		<link>http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-32367</link>
		<dc:creator>Mike G</dc:creator>
		<pubDate>Thu, 07 Jul 2011 00:03:45 +0000</pubDate>
		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-32367</guid>
		<description>Thanks for this. It is a very helpful write-up.</description>
		<content:encoded><![CDATA[<p>Thanks for this. It is a very helpful write-up.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Kamil Wojcicki</title>
		<link>http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-32350</link>
		<dc:creator>Kamil Wojcicki</dc:creator>
		<pubDate>Tue, 28 Jun 2011 22:30:17 +0000</pubDate>
		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-32350</guid>
		<description>Use of and iteration over struct fields can result in cleaner and more reusable code. This is especially the case for very frequently used functionalities. Say, for example, we wanted to frequently process audio signals. Here is a basic example:

&lt;pre&gt;
clear all; close all; clc; fprintf(&#039;.\n&#039;);

    % SNR computation function handle
    SNR = @(x,y)( 20*log10(norm(x)/norm(x(:)-y(:))) );

    % read stimuli from files
    [ speech.clean, fs ] = wavread( &#039;clean.wav&#039; );
    speech.noisy = wavread( &#039;noisy.wav&#039; );  

    % add extra stimuli below, e.g.,
    speech.noise = speech.noisy - speech.clean;
    % speech.enhanced = some_method( speech.noisy, ... );

    % iterate over stimuli    
    stimuli = fieldnames( speech );
    S = length( stimuli );         
    for s = 1:S 
        stimulus = stimuli{s};

        % do something with the current stimulus, e.g., 
        snr.(stimulus) = SNR( speech.clean, speech.(stimulus) );
        fprintf( &#039;SNR: %0.2f\n&#039;, snr.(stimulus) );
    end
&lt;/pre&gt;

Sometimes, it can be useful to exclude some fields from consideration. This can be easily achieved using the ismember function:

&lt;pre&gt;
    stimuli = stimuli( ~ismember(stimuli,{&#039;clean&#039;,&#039;enhanced&#039;,&#039;etc&#039;}) );
&lt;/pre&gt;

The second (cell array) argument to the ismember function above holds the list of field names to be excluded from the stimuli array.

If the exclusion of elements is not a concern, then the for-loop based iteration shown in the first example can be written more compactly, at a cost of somewhat reduced readability, as follows:

&lt;pre&gt;
    for stimulus = fieldnames( speech )&#039;

        % do something with the current stimulus, e.g., 
        snr = SNR( speech.clean, speech.(stimulus{1}) ); 
        fprintf( &#039;SNR: %0.2f\n&#039;, snr );
    end
&lt;/pre&gt;

Note that the transpose on the output of the fieldnames function in the above example is important since MATLAB&#039;s for-loops operate on per column basis. Also, since the stimulus at each iteration is a cell array with a single string element, we need to extract its string value for use as a dynamic field name of a structure (i.e., using the {1} postscript).

Finally, once a given functionality is implemented, we would like to do as few changes as possible to the code in its future reuse. At the same time we would like the code to nicely scale for different number of inputs. Say for example we wanted to plot audio signals while being able to add new/extra inputs in the future, but without changing the rest of the code. Structure iterators nicely facilitate such automatic scalability. Consider the example below:

&lt;pre&gt;    
    % iterate over stimuli    
    stimuli = fieldnames( speech );
    S = length( stimuli );
    figure( &#039;Position&#039;, [ 100 100 800 200*S ], ...
                &#039;PaperPositionMode&#039;, &#039;auto&#039;, &#039;color&#039;, &#039;w&#039; );
    for s = 1:S
        stimulus = stimuli{s};
        time = [0:length(speech.(stimulus))-1]/fs;

        % plot current stimulus
        subplot( S, 1, s );
        plot( time, speech.(stimulus), &#039;k-&#039; );
        xlim( [min(time) max(time)] );
        xlabel( &#039;Time (s)&#039; ); ylabel( &#039;Amplitude&#039; );
        title( sprintf(&#039;%s%s&#039;,upper(stimulus(1)),stimulus(2:end)) );
    end

    % print figure to png
    print( &#039;-dpng&#039;, sprintf(&#039;%s.png&#039;,mfilename) );
&lt;/pre&gt;

The above code extends the functionality of the first example with stimuli plots. In principle, future reuse for new audio signals only requires specification of the new audio samples as fields of the speech structure. The remaining code will scale automatically to produce plots for all defined signals.</description>
		<content:encoded><![CDATA[<p>Use of and iteration over struct fields can result in cleaner and more reusable code. This is especially the case for very frequently used functionalities. Say, for example, we wanted to frequently process audio signals. Here is a basic example:</p>
<pre>
clear all; close all; clc; fprintf('.\n');

    % SNR computation function handle
    SNR = @(x,y)( 20*log10(norm(x)/norm(x(:)-y(:))) );

    % read stimuli from files
    [ speech.clean, fs ] = wavread( 'clean.wav' );
    speech.noisy = wavread( 'noisy.wav' );  

    % add extra stimuli below, e.g.,
    speech.noise = speech.noisy - speech.clean;
    % speech.enhanced = some_method( speech.noisy, ... );

    % iterate over stimuli
    stimuli = fieldnames( speech );
    S = length( stimuli );
    for s = 1:S
        stimulus = stimuli{s};

        % do something with the current stimulus, e.g.,
        snr.(stimulus) = SNR( speech.clean, speech.(stimulus) );
        fprintf( 'SNR: %0.2f\n', snr.(stimulus) );
    end
</pre>
<p>Sometimes, it can be useful to exclude some fields from consideration. This can be easily achieved using the ismember function:</p>
<pre>
    stimuli = stimuli( ~ismember(stimuli,{'clean','enhanced','etc'}) );
</pre>
<p>The second (cell array) argument to the ismember function above holds the list of field names to be excluded from the stimuli array.</p>
<p>If the exclusion of elements is not a concern, then the for-loop based iteration shown in the first example can be written more compactly, at a cost of somewhat reduced readability, as follows:</p>
<pre>
    for stimulus = fieldnames( speech )'

        % do something with the current stimulus, e.g.,
        snr = SNR( speech.clean, speech.(stimulus{1}) );
        fprintf( 'SNR: %0.2f\n', snr );
    end
</pre>
<p>Note that the transpose on the output of the fieldnames function in the above example is important since MATLAB&#8217;s for-loops operate on per column basis. Also, since the stimulus at each iteration is a cell array with a single string element, we need to extract its string value for use as a dynamic field name of a structure (i.e., using the {1} postscript).</p>
<p>Finally, once a given functionality is implemented, we would like to do as few changes as possible to the code in its future reuse. At the same time we would like the code to nicely scale for different number of inputs. Say for example we wanted to plot audio signals while being able to add new/extra inputs in the future, but without changing the rest of the code. Structure iterators nicely facilitate such automatic scalability. Consider the example below:</p>
<pre>
    % iterate over stimuli
    stimuli = fieldnames( speech );
    S = length( stimuli );
    figure( 'Position', [ 100 100 800 200*S ], ...
                'PaperPositionMode', 'auto', 'color', 'w' );
    for s = 1:S
        stimulus = stimuli{s};
        time = [0:length(speech.(stimulus))-1]/fs;

        % plot current stimulus
        subplot( S, 1, s );
        plot( time, speech.(stimulus), 'k-' );
        xlim( [min(time) max(time)] );
        xlabel( 'Time (s)' ); ylabel( 'Amplitude' );
        title( sprintf('%s%s',upper(stimulus(1)),stimulus(2:end)) );
    end

    % print figure to png
    print( '-dpng', sprintf('%s.png',mfilename) );
</pre>
<p>The above code extends the functionality of the first example with stimuli plots. In principle, future reuse for new audio signals only requires specification of the new audio samples as fields of the speech structure. The remaining code will scale automatically to produce plots for all defined signals.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Loren</title>
		<link>http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-29603</link>
		<dc:creator>Loren</dc:creator>
		<pubDate>Fri, 18 Jul 2008 14:53:31 +0000</pubDate>
		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-29603</guid>
		<description>Ljubomir-

That&#039;s the same way I iterated above.  It&#039;s a bit clunky getting the contents of the scalar cell, but it is the way to iterate on a cell array.

--Loren</description>
		<content:encoded><![CDATA[<p>Ljubomir-</p>
<p>That&#8217;s the same way I iterated above.  It&#8217;s a bit clunky getting the contents of the scalar cell, but it is the way to iterate on a cell array.</p>
<p>&#8211;Loren</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Ljubomir Josifovski</title>
		<link>http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-29602</link>
		<dc:creator>Ljubomir Josifovski</dc:creator>
		<pubDate>Fri, 18 Jul 2008 14:43:27 +0000</pubDate>
		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-29602</guid>
		<description>Got caught by this today - iterate through strings list:

&gt;&gt; for a = {&#039;b&#039;, &#039;c&#039;}; a, end;
a = &#039;b&#039;
a = &#039;c&#039;

But actually

&gt;&gt; whos a
  Name      Size            Bytes  Class    Attributes
  a         1x1                62  cell 

is not a string - one needs to

&gt;&gt; for a = {&#039;b&#039;, &#039;c&#039;}; a=a{1}, end;

which I find inpractical + ugly. Am I missing something/is there a better way to iterate through strings list?

thanks,
Ljubomir</description>
		<content:encoded><![CDATA[<p>Got caught by this today &#8211; iterate through strings list:</p>
<p>&gt;&gt; for a = {&#8216;b&#8217;, &#8216;c&#8217;}; a, end;<br />
a = &#8216;b&#8217;<br />
a = &#8216;c&#8217;</p>
<p>But actually</p>
<p>&gt;&gt; whos a<br />
  Name      Size            Bytes  Class    Attributes<br />
  a         1&#215;1                62  cell </p>
<p>is not a string &#8211; one needs to</p>
<p>&gt;&gt; for a = {&#8216;b&#8217;, &#8216;c&#8217;}; a=a{1}, end;</p>
<p>which I find inpractical + ugly. Am I missing something/is there a better way to iterate through strings list?</p>
<p>thanks,<br />
Ljubomir</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: per isakson</title>
		<link>http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-27881</link>
		<dc:creator>per isakson</dc:creator>
		<pubDate>Fri, 28 Mar 2008 16:01:15 +0000</pubDate>
		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-27881</guid>
		<description>Ljubomir-

The foreach-functionality is included in Matlab&#039;s FOR - isn&#039;t it?. More often than not, my for-loops are through cell and structured arrays. The arrays may hold anything even funtionhandles of nested functions. Are cell arrays less powerful than collections?

It took me some time to appreiciate the full power of the for-loops in Matlab. 

- per</description>
		<content:encoded><![CDATA[<p>Ljubomir-</p>
<p>The foreach-functionality is included in Matlab&#8217;s FOR &#8211; isn&#8217;t it?. More often than not, my for-loops are through cell and structured arrays. The arrays may hold anything even funtionhandles of nested functions. Are cell arrays less powerful than collections?</p>
<p>It took me some time to appreiciate the full power of the for-loops in Matlab. </p>
<p>- per</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Loren</title>
		<link>http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-27879</link>
		<dc:creator>Loren</dc:creator>
		<pubDate>Fri, 28 Mar 2008 15:02:05 +0000</pubDate>
		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-27879</guid>
		<description>Ljubomir-

Depending on the collection, there&#039;s cellfun, arrayfun, and structfun.  And yes, you can use A(:).&#039; to make a single row.  Or you can use reshape(A,1,[]).

I&#039;m glad the editor warning on loop variables is helpful to you.

--Loren</description>
		<content:encoded><![CDATA[<p>Ljubomir-</p>
<p>Depending on the collection, there&#8217;s cellfun, arrayfun, and structfun.  And yes, you can use A(:).&#8217; to make a single row.  Or you can use reshape(A,1,[]).</p>
<p>I&#8217;m glad the editor warning on loop variables is helpful to you.</p>
<p>&#8211;Loren</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Ljubomir Josifovski</title>
		<link>http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-27877</link>
		<dc:creator>Ljubomir Josifovski</dc:creator>
		<pubDate>Fri, 28 Mar 2008 14:50:09 +0000</pubDate>
		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-27877</guid>
		<description>More generally, Matlab lacks &quot;foreach&quot; construct where one can iterate through a collection without the need to introduce an index.** 

I have settled for a variant of solution 2. I&#039;d use &quot; for str = fn(:)&#039; &quot;. The column operator is to make sure I get to a row regardless if &quot; fn &quot; is row or column. (ie context independent - maybe there is a single &quot;make row&quot; operator instead of &quot; (:)&#039; &quot; ?)

- Ljubomir


**Unneeded indices are bad. Not needing them for anything else but to get to the value, one tends to choose the obvious i,j,k without sufficient attention so may well overwrite the same named loop vars in an outer loop. The editor warns so is of great help here.</description>
		<content:encoded><![CDATA[<p>More generally, Matlab lacks &#8220;foreach&#8221; construct where one can iterate through a collection without the need to introduce an index.** </p>
<p>I have settled for a variant of solution 2. I&#8217;d use &#8221; for str = fn(:)&#8217; &#8220;. The column operator is to make sure I get to a row regardless if &#8221; fn &#8221; is row or column. (ie context independent &#8211; maybe there is a single &#8220;make row&#8221; operator instead of &#8221; (:)&#8217; &#8221; ?)</p>
<p>- Ljubomir</p>
<p>**Unneeded indices are bad. Not needing them for anything else but to get to the value, one tends to choose the obvious i,j,k without sufficient attention so may well overwrite the same named loop vars in an outer loop. The editor warns so is of great help here.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Loren</title>
		<link>http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-25811</link>
		<dc:creator>Loren</dc:creator>
		<pubDate>Tue, 05 Feb 2008 13:18:13 +0000</pubDate>
		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-25811</guid>
		<description>Andrew-

I don&#039;t see how you can do it simply for your set up since you have both cells and numeric arrays and the same functions don&#039;t operate on both and structfun wants one function (though I guess it could be a complicated one).  Besides, for non-uniform output, structfun outputs a struct so I can&#039;t see how you&#039;re better off.

--Loren</description>
		<content:encoded><![CDATA[<p>Andrew-</p>
<p>I don&#8217;t see how you can do it simply for your set up since you have both cells and numeric arrays and the same functions don&#8217;t operate on both and structfun wants one function (though I guess it could be a complicated one).  Besides, for non-uniform output, structfun outputs a struct so I can&#8217;t see how you&#8217;re better off.</p>
<p>&#8211;Loren</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Andrew</title>
		<link>http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-25810</link>
		<dc:creator>Andrew</dc:creator>
		<pubDate>Tue, 05 Feb 2008 13:00:50 +0000</pubDate>
		<guid isPermaLink="false">http://blogs.mathworks.com/loren/2007/08/15/iterating-over-non-numeric-values/#comment-25810</guid>
		<description>Thanks Loren for the reply, but I am looking for a solution that takes the structure and places its contents into a cell array, without having to specify the individual fieldnames. That is why I was looking at structfun. In the end I think struct2cell will do the trick with the use of num2cell, but for the &quot;fun&quot; of it, could it be done with structfun?</description>
		<content:encoded><![CDATA[<p>Thanks Loren for the reply, but I am looking for a solution that takes the structure and places its contents into a cell array, without having to specify the individual fieldnames. That is why I was looking at structfun. In the end I think struct2cell will do the trick with the use of num2cell, but for the &#8220;fun&#8221; of it, could it be done with structfun?</p>
]]></content:encoded>
	</item>
</channel>
</rss>

