fopen with string vector

5 Ansichten (letzte 30 Tage)
Amanda Kessler
Amanda Kessler am 26 Aug. 2019
Kommentiert: Jon am 27 Aug. 2019
clear all
clc
cd('C:\Users\akess\Box Sync\PhD\PCCS\PCCS 190822\HRP with salt 190822\Textfiler')
S = dir('*.txt');
N = {S.name};
for j=1:length(N)
x = ones(2,length(N));
Name=N(j);
fid = fopen(Name); %THIS DOESNT WORK, DO YOU KNOW HOW TO FIX IT?
data = textscan(fid,'%s%s%s');
A=data{1, 2}{132, 1};%mean count rate ch.1
B=data{1, 2}{134, 1};%mean count rate ch.2
A1=str2num(A);
B1=str2num(B);
x(1,j) = A1;
x(2,j) = B1;
end
I have several files I want to read and only take out certain values. I would like the loop to open one file at a time but fopen does not seem to work with taking out one string from N. Can anyone help me?
  2 Kommentare
JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH am 26 Aug. 2019
try it :
clear all
clc
cd('C:\Users\akess\Box Sync\PhD\PCCS\PCCS 190822\HRP with salt 190822\Textfiler')
S = dir('*.txt');
N = {S.name};
for j=1:length(N)
x = ones(2,length(N));
Name=N{j};
fid = fopen(Name); %THIS DOESNT WORK, DO YOU KNOW HOW TO FIX IT?
data = textscan(fid,'%s%s%s');
A=data{1, 2}{132, 1};%mean count rate ch.1
B=data{1, 2}{134, 1};%mean count rate ch.2
A1=str2num(A);
B1=str2num(B);
x(1,j) = A1;
x(2,j) = B1;
close(fid)
end
Amanda Kessler
Amanda Kessler am 27 Aug. 2019
Thank you! works perfectly

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jon
Jon am 26 Aug. 2019
Bearbeitet: Jon am 26 Aug. 2019
Your first problem is that dir returns a structure. If you want the name of, the ith file it returns you should use
Name = S(j).name
You could also do it your way, making a cell array of file names, but I don't see any advantage to that. If you do it that way however you must use curly braces to retrieve the individual name for example
Name = N{j}
  2 Kommentare
Amanda Kessler
Amanda Kessler am 27 Aug. 2019
Thank you! Works!
Jon
Jon am 27 Aug. 2019
Glad that it works now.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Low-Level File I/O finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by