How to import a spesific variable from a matrix in a file?
조회 수: 4 (최근 30일)
이전 댓글 표시
I have a file "SANJOSE" that has two values in it "20 30"
I would like to use "loc1lat = importdata('SANJOSE')" command to import the first value of the 1x2 matrix, not the whole thing.
I am not sure what syntax to use after ('SANJOSE', ???) to specify which variable in the matrix I want.
Thanks
댓글 수: 2
채택된 답변
José-Luis
2012년 9월 18일
편집: José-Luis
2012년 9월 18일
filename = 'SANJOSE';
(SANJOSE is a text file containing one line: 20 30)
Two options, either pass the file name SANJOSE as a string:
fid = fopen('SANJOSE','r'); %'r' means you only want to read the data.
your_value = fscanf(fid,'%d',1); %Will only read the first value
fclose(fid);
Or, pass the variable name (filename) that contains a string:
fid = fopen(filename,'r');
your_alternative_value = fscanf(fid,'%d',1);
fclose(fid);
댓글 수: 4
José-Luis
2012년 9월 18일
편집: José-Luis
2012년 9월 18일
My bad, I had not tested the code I posted above: it would work only if you want to skip one value. Instead you could move in your file character by character until you find a space and then read the next variable.
filename = 'SANJOSE';
fid = fopen('SANJOSE','r');
valsToSkip = 2; %1 if you want the second value, 2 if your want the third, etc...
while (valsToSkip)
currentChar = fscanf(fid,'%c',1);
if currentChar == ' ';
valsToSkip = valsToSkip - 1;
end
end
your_second_value = fscanf(fid,'%d',1);
fclose(fid);
fid = fopen(filename,'r');
your_first_value = fscanf(fid,'%d',1);
fclose(fid);
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Convert Image Type에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!