Search code examples
arraysmatlabmatrixprintfcell-array

MATLAB fprintf printing cell array to text file


I am attempting to use the MATLAB fprintf command to print a delimited table of strings stored in a vector to a text file. Which strings from the vector are chosen and printed depends on a matrix which is constructed in the main while loop of the program. However, when I try to run the code, MATLAB gives me an error that the "Subscript indices must be either positive integers or logical." An example matrix and examples string arrays, along with my current fprintf code are given. I'd really like to understand what is going here, as well as any hope or pointers on how to maybe set it up better. The matrix and cell arrays are actual examples I get when running the program. Thanks in advance!

Pitches={'Fastball','Curveball','Screwball','Riseball','Changeup','Dropball'};
tp={'Strike','Ball'};
ResultHit={'Single','Double','Triple','Home Run','Bunt','ROE'};
ResultOut={'Strikeout','Groundout','Flyout','Foulout'};

M= [4,1,0,0;2,2,0,0;3,1,0,0;5,1,1,0];


fileID = fopen('gamedata.txt','w');

for i=1:length(M)

    fprintf(fileID,'%s %s %s %s\n',Pitches{M(i,1)},tp{M(i,2)},...
    ResultHit{M(i,3)},ResultOut{M(i,4)});

end

fclose(fileID);

Solution

  • The M matrix has zeroes in the third and fourth columns:

    M =
    
     4     1     0     0
     2     2     0     0
     3     1     0     0
     5     1     1     0
    

    And so when the code begins iterating in the for loop, M(1,3) and M(1,4) are both zeros and are invalid indices into the ResultHit and ResultOut arrays…hence the error message (indices must be positive integers).

    I think what you need are 'N/A' strings in your ResultHit and ResultOut arrays which correspond to there being no hit or no out on that pitch. These could both be in the first position of the array, and the M from above changed to

    M =
    
     4     1     1     1
     2     2     1     1
     3     1     1     1
     5     1     2     1
    

    This should allow the code to progress.