Matlab错误:()-索引必须出现在索引表达式的最后 [英] Matlab Error: ()-indexing must appear last in an index expression

查看:3079
本文介绍了Matlab错误:()-索引必须出现在索引表达式的最后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,想在制表符分隔的txt文件中写一个数组:

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);

但我收到此错误:

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

我应该怎么称呼s(x)(1)? s是一个数组

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})) ; 

推荐答案

使用MATLAB,您必须先将()赋给一个临时变量,然后才能立即使用()索引该函数的结果(八度允许这样做).这是由于您允许这样做时出现的一些歧义.

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)) ;

尚不清楚您的数据结构到底是什么,但看起来s是一个单元格,因此您实际上应该使用{}索引来访问其内容

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});

更新

如果您尝试从输入文件中读取单个单词,然后将其写到制表符分隔的文件中,则可能会执行以下操作:

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)

这篇关于Matlab错误:()-索引必须出现在索引表达式的最后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆