How to select two columns of data based on flag present in 3rd column from a text file using Matlab
3 次查看(过去 30 天)
显示 更早的评论
Hi All,
I want to pull out first and second column only if my flag is 1 in 3rd column and skip if it is zero.
My file contents is type
10 20 0
5 11 1
6 7 1
20 9 0
100 3 1
12 5 1
.......
I have tried like
dd=fopen('extract.txt');
mm=fopen('output.txt','w');
for i=1:207
if dd(i,3)==0
disp('skip');
else dd(i,3)=1
fprintf(mm,'%d\t%d\n',dd(i,3));
end
end
It is showing error. How can I achieve this.
Thanks In Advance
0 个评论
回答(2 个)
Walter Roberson
2017-7-23
dd = fopen('extract.txt');
mm = fopen('output.txt','w');
for i=1:207
if dd(i,3) == 0
fprintf('skip 0 at i = %d\n', i);
elseif dd(i,3) == 1
fprintf('found 1 at i = %d, recording line\n', i);
fprintf(mm,' %d\t%d\n',dd(i,1), dd(i,2));
else
fprintf('found unexpected value %g at i = %d, skipping it\n', dd(i,3), i);
end
end
fclose(mm)
But if you do not need those 'skip' and so on messages, then you can replace all of it with
dd = fopen('extract.txt');
selected = dd(dd(:,3) == 1, 1:2);
mm = fopen('output.txt','w');
fprintf(mm,' %d\t%d\n', selected .'); %transpose is important
fclose(mm)
Image Analyst
2017-7-23
Why not simply read the whole thing in and extract the rows you need?
data = csvread(filename); % Read in all the data. Can also use importdata().
rowsToExtract = data(:, 3) == 1; % Find rows with 1 in column 3
% Extract columns 1 and 2 but only those rows.
data = data(rowsToExtract, 1:2);
4 个评论
Image Analyst
2017-7-23
You can use sprintf() and fprintf() to make a nicely aligned table if you use a non-proportional font, like Courier. You might also want to use a spreadsheet-like control called a "uitable" on your GUI.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!