我已经查看了here和here,但我不确定是否找到了我需要的内容。
我有一个看起来像
的不规则文件(代表粒子1到5的邻居)2 3 5
1 3
1 2
1
我想弄清楚加载它的方式(作为'称为A
的东西)并执行以下操作:
size(A(1,:))
应该给我3
)B
(大小为5),选择与行给出的索引相对应的B元素(B(A(1,:))
之类的内容会给我[B(2) B(3) B(5)]
)答案 0 :(得分:1)
Since you want arrays with size depending on their first index, you're probably left with cell
s. Your cell A
could be such that A{1}
equals to [2 3 5]
and A{2}
to [1 3]
in your example etc. To do this you can read your file infile
by
fid=fopen(infile,'rt');
A=[];
while 1
nextline=fgets(fid);
if nextline==-1 %EOF reached
break;
end
A{end+1}=sscanf(nextline,'%d');
end
fclose(fid);
%demonstrate use for indexing
B=randi(10,5,1);
B(A{3}) %2-element vector
B(A{4}) %empty vector
Then A{i}
is a vector corresponding to the i
th line in your file. If the line is empty, then it's the empty vector. You can use it to index B
as you want to, see the example above. Note that you should not add a newline at the very end of your infile
, otherwise you'll have a spurious empty element for A
. If you know in advance how many lines you need to read, this is not an issue.
And the number of entries in line i
are given by length(A{i})
, with i=1:length(A)
.