Iteration over Matlab struct elements

Matlab / Octave programming forum.

Iteration over Matlab struct elements

Postby kamil on February 16th, 2008, 8:32 pm

In Matlab programs simple scalar iteration can be used to go over array elements, i.e.
Code: Select all
for n = 1:length(array)
    disp( array(n) ); % or disp( array{n} ); if array is a cell array
end

However, in some instances it maybe better to use descriptive names for elements of an array . The functionality I am talking about is f.e. similar to perl hash arrays. To accomplish this in Matlab you could use enums, i.e. allocate index values to variables with meaningful names. That approach is quite crude however. Another way is to use Matlab's structs. Below is a simple mock-up example of struct approach including the different approaches for element iteration.
Code: Select all
clear all; close all; clc;

    [ v.speech.x, v.speech.fs, v.speech.nbits ] = wavread('speech.wav');
    [ v.musik.x,  v.musik.fs,  v.musik.nbits  ] = wavread('musik.wav');

    elements = fieldnames(v);

    % first approach
    for n = 1:length(elements)
        disp( v.(elements{n}) )
    end

    % second approach
    for n = elements.'
        disp( v.(char(n)) )
    end

    % third approach
    structfun(@(x) disp( x ), v);

The above outputs:
Code: Select all
        x: [29031x1 double]
        fs: 8000
        nbits: 16

        x: [66782x1 double]
        fs: 25000
        nbits: 16

        x: [29031x1 double]
        fs: 8000
        nbits: 16

        x: [66782x1 double]
        fs: 25000
        nbits: 16

        x: [29031x1 double]
        fs: 8000
        nbits: 16

        x: [66782x1 double]
        fs: 25000
        nbits: 16

:arrow: Here is the original article reference: Iterating over Non-Numeric Values

This is getting close to object oriented programming, but not quite there. Next step further would be to implement actual objects with their own properties as well as functions, including iterators: MATLAB Classes and Objects.
User avatar
kamil
Linux Adept
 
Posts: 118
Joined: January 18th, 2008, 1:22 am
Location: Brisbane, Australia

Return to Matlab

Who is online

Users browsing this forum: No registered users and 0 guests

cron

dsplabs homelinux bloglinux forums new! travel photographyawklores new! cryptographyjames' home
©2009 dsplabs.com.au