Matlab Error: ()-indexing must appear last in an index expression

前端 未结 1 1594
孤城傲影
孤城傲影 2021-01-16 17:56

I have this code and want to write an array in a tab delimited txt file :

fid = fopen(\'oo.txt\', \'wt+\');
for x = 1 :length(s)
fprintf(fid, \'%s\\t\\n\',           


        
相关标签:
1条回答
  • 2021-01-16 18:50

    With MATLAB, you cannot immediately index into the result of a function using () without first assigning it to a temporary variable (Octave does allow this though). This is due to some of the ambiguities that happen when you allow this.

    tmp = s(x);
    fprintf(fid, '%s\t\n',  tmp(1)) ;
    

    There are some ways around this but they aren't pretty

    It is unclear what exactly your data structure is, but it looks like s is a cell so you should really be using {} indexing to access it's contents

    fprintf(fid, '%s\t\n', s{x});
    

    Update

    If you're trying to read individual words in from your input file and then write those out to a tab-delimited file, I'd probably do something like the following:

    fid = fopen('input.txt', 'r');
    contents = fread(fid, '*char')';
    fclose(fid)
    
    % Break a string into words and yield a cell array of strings
    words = regexp(contents, '\s+', 'split');
    
    % Write these out to a file separated by tabs
    fout = fopen('output.tsv', 'w');
    fprintf(fout, '%s\t', words{:});
    fclose(fout)
    
    0 讨论(0)
提交回复
热议问题