Writing to file with loops and loop error
3 次查看(过去 30 天)
显示 更早的评论
Hello, Here is my current code:
clc;
clear;
clear segarray;
block_size = 10000;
filename = 'brktorque-vel-navgraph.txt';
FormatString = ['%*s %s %s %s %s %s %s'];
fid = fopen(filename);
cellchunk = textscan(fid,FormatString,1,'delimiter','\t');
while ~feof(fid)
tic
segarray = textscan(fid, FormatString, block_size, 'delimiter',char(9));
for i = 1 : 6(segarray);
segarray{i} = str2double(segarray{i}) ;
isn = isnan(segarray{i}) ;
segarray{i}(isn) = 0 ;
end
toc
[b, ~, n] = unique(segarray(:,6) , 'stable');
firstColumn = accumarray(n , segarray(:,4) , size(b) , @(x) min(x));
secondColumn = accumarray(n , segarray(:,5) , size(b) , @(x) max(x));
thirdColumn = accumarray(n , segarray(:,3) , size(b) , @(x) mode(x));
outputArray = cat(2 , firstColumn , secondColumn , thirdColumn, b);
csvwrite('brktorque-vel-navgraph-agg.csv',outputArray)
end
fclose(fid);
I have two questions, hopefully you all can provide some assistance: 1. I'm having trouble in the second iteration of my loop with the unique function. The error is "Error using cell/unique (line 86) Input A must be a cell array of strings." I'm not sure why this is happening. 2. I'm worried that my loop will overwrite what is being written to the file in each iteration. I actually want the output of each iteration to be saved after the previous output and all in one file. Am I doing this correctly?
Any help would be greatly appreciated. Thanks in advance!
2 个评论
Jan
2014-2-28
What does this mean:
for i = 1 : 6(segarray);
This is no valid Matlab syntax and inconsequence the code should not run at all.
回答(1 个)
per isakson
2014-2-28
1. Probably segarray(:,6) is empty
>> unique({[]})
Error using cell/unique (line 86)
Input A must be a cell array of strings.
2. csvwrite has no option to append to file. You need to use a function with an append-option, e.g. fopen together with fprintf
Why the while loop?
.
2 个评论
per isakson
2014-3-4
编辑:per isakson
2014-3-4
You have not described the goal and your constraints well enough.
- How large is the text file?
- How much physical memory (ram) is it in the computer?
- Is speed a real problem?
- Is the format of the file known? What is the purpose of cellchunk
"[...] in a faster way?" Yes, most likely.
- Use the largest possible value of blocksize that memory allows
- Read and convert to numerical in one step with textscan
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!