mary
mary

Reputation: 267

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

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',  s(x)(1)) ;
end; 
fclose(fid);

but I receive this error :

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

how should i call s(x)(1)? s is an array

 s <2196017x1 cell>

when I use this code I get no error but return me some characters not words.

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

Upvotes: 0

Views: 1115

Answers (1)

Suever
Suever

Reputation: 65430

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)

Upvotes: 1

Related Questions