- 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
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.
