I have already looked here and here , but I'm not sure I found what I need.
I have an irregular file (that represents neighbors of particles 1 to 5) that looks like that
2 3 5
1 3
1 2
1
I am want to figure out a way to load it (as 'something' called A
) and do the following things:
size(A(1,:))
shall give me 3
)B
(of size 5) select the elements of B corresponding to the indices given by a line (something like B(A(1,:))
shall give me [B(2) B(3) B(5)]
)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)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.