Search code examples
arraysmatlabprintfcell-array

Printing information from a cell array with for loops


I'm trying to create a function here called 'crewsize' that takes an airspace cell array (the cell array 'airspace' will be shown below), and the output will print using fprintf a table of flight numbers and the number of people in the crew. The airspace cell array looks like this

airspace = 

'BF 123'     [  515.2000]    [ 90]    [154]    'Behnam Jane Jill...'    'Montreal'       [22000]    [1x2 double]
'VS0 456'    [   99.6000]    [270]    [ 31]    'Frances, Jake, J...'    'Los Angeles'    [21000]    [1x2 double]
'BF 8421'    [1.5057e+03]    [170]    [  0]    'Giuseppe, Susan'        'Calgary'        [33000]    [1x2 double]
'AB 896'     [       500]    [ 90]    [132]    'Hao, Ashraf, Sue'       'Montreal'       [33000]    [1x2 double]

The [1x2 double column] can be neglected for this question. As for the function, I'm completely lost and not sure how to proceed from my code, I don't understand the concept of fprintf and would really like some help! My code for the function so far is:

function crewsize(airspace)
for k = 1:4
a = airspace(k);
b = airspace{k,5};
fprintf('Flight Number  Crew Size\n %5.1f %5.1f',a,b)

Any help on this would be greatly appreciated. Again, for the output I'm trying to print just the flight numbers (The 1st column) and the number of people on that crew (5th column)

Thank you all!


Solution

  • You should use the %s and %i formatSpecs (for strings and integers). There is also a slight difficulty for counting the number of crew members from the string, but you can use either strsplit (in recent releases) or the regexp functions.

    In practice:

    function crewsize(airspace)
    
    for k = 1:4
        a = airspace{k,1};
        b = numel(regexp(airspace{k,5}, ' ', 'split'));
        fprintf('Flight Number: %s - Crew Size: %i\n',a,b);
    end
    

    Best,