How to select two columns of data based on flag present in 3rd column from a text file using Matlab

조회 수: 1 (최근 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

답변 (2개)

Walter Roberson
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)
  댓글 수: 1
POKA
POKA 2017년 7월 23일
Thanks for your suggestions. I solved it through other way . I will check your one also .If you remember yesterday's problem , I have pulled Raim and Gga line to different file and filter them out using 5(flag). I have same number of Raim and Gga lines . So it is solved now . Thanks

댓글을 달려면 로그인하십시오.


Image Analyst
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
POKA
POKA 2017년 7월 23일
Just asking ,is it possible to give stylish apperaness of output MATLAB figure . something we see in power point presentation or sometimes our desktop display. Can we manipulate output MATLAB figure to get impressive one instead of general pop up . wanted to learn . Thanks
Image Analyst
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by