Changes

Jump to navigation Jump to search
1,413 bytes added ,  00:26, 26 August 2012
Line 32: Line 32:     
== Input/output ==
 
== Input/output ==
 +
=== Display matched elements from different arrays ===
 +
==== Problem ====
 +
You have two, or more, arrays with paired elements and want to print out a string about them. For example:
 +
 +
    keys  = {"human",  "mouse", "chicken"};
 +
    values = [ 64        72      70      ];
 +
 +
and you want to display:
 +
 +
    Calculated human genome GC content is 64%
 +
    Calculated mouse genome GC content is 72%
 +
    Calculated chicken genome GC content is 70%
 +
 +
==== Solution ====
 +
Make a two rows cell array, with each paired data in a column and supply a cs-list to printf
 +
 +
    values = num2cell (values);
 +
    new    = {keys{:}; values{:}};
 +
    printf ("Calculated %s genome GC content is %i%%\n", new{:})
 +
 +
or in a single line:
 +
    printf ("Calculated %s genome GC content is %i%%\n", {keys{:}; num2cell(values){:}}{:})
 +
   
 +
 +
==== Discussion ====
 +
{{Codeline|printf}} and family do not accept cell arrays as values. However, they keep repeating the template given as long as it has enough arguments to keep going. As such, the trick is on supplying a cs-list of elements which can be done by using a cell array and index it with {{Codeline|<nowiki>{}</nowiki>}}.
 +
 +
Since values are stored in column-major order, paired values need to be on the same column. A new row of data can then be added later with {{Codeline|new(end+1,:) <nowiki>= {"Andrew", "Bob", "Kevin"}</nowiki>}}. Note that normal brackets are now being used for indexing.
 +
 
=== Swap values ===
 
=== Swap values ===
 
If you want to exchange the value between two variables without creating a dummy one, you can simply do:
 
If you want to exchange the value between two variables without creating a dummy one, you can simply do:

Navigation menu