Matlab: Select a variable name and find the corresponding value - matlab

Can somebody explain me how i get some specific values after the = sign? The input File is a .subvar file format.
I dont know how to jump in the right row and column to get the value. Do you have a matlab tutorial link for such a problem.
I need for example two specific values (after the = sign):
The value of $_Wk1_lr_m and $_Wk1_voll_m
!file.version=1.543!
! Testautomatisch
subvargroup.begin ($G_Wk1)
subvar( $_Wk1_lr_C_x, str = ' 0.019 ' )
subvar( $_Wk1_lr_m, str = ' 15601 ' ) ! [kg] lr
subvar( $_Wk1_lr_C_y, str = '-0.007 ' )
subvar( $_Wk1_lr_C_z, str = ' 1.644 ' )
subvar( $_Wk1_voll_m, str = ' 33690 ' ) ! [kg] voll
subvargroup.end ($G_Wk1)
What are the first steps to get the right row and the right column? Thank you and stay at home :)

read the file line by line, match the line format and extract the values using regular expression regexp
fid=fopen('mydata.subvars','rt');
res=struct;
while(~feof(fid))
line=fgetl(fid);
if(regexp(line,'^\s*subvar\(','once'))
val=regexp(line,'\$_(\w+),\s*str\s*=\s*''\s*([0-9.-]+)\s*','tokens');
if(length([val{:}])==2)
res.(val{1}{1})=str2num(val{1}{2});
end
end
end
fclose(fid);
here is the result
>> res
res =
Wk1_lr_C_x: 0.0190
Wk1_lr_m: 15601
Wk1_lr_C_y: -0.0070
Wk1_lr_C_z: 1.6440
Wk1_voll_m: 33690

Related

MATLAB how to automatically read a number of files

I would like to plot a number of 3D graphs from different data files. For example I am using
fid = fopen('SS 1.dat','r');
to read the first file and then plot a graph. How to set the program to change the name to 'SS 2.dat' automatically? Also for the tenth file the name becomes 'SS 10.dat' which has one space less (i.e.only two space between SS and 10) then the first to ninth files. How to set the program to adjust for that? Thank you.
Use dir:
filenames = dir('*.dat'); %//gets all files ending on .dat in the pwd
for ii =1:length(filenames)
fopen(filenames(ii),'r');
%//Read all your things and store them here
end
The beauty of dir as opposed to the other solutions here is that you can get the contents of the pwd (present working directory) in one single line, regardless of how you called your files. This makes for easier loading of files, since you do not have any hassle with dynamic file names.
The following code displays a lazy way to print the names from 1 to 999 that you mentioned:
for ii=1:999
ns = numel(num2str(ii));
switch ns
case 1
fname = ['ss ' num2str(ii) '.dat'];
case 2
fname = ['ss ' num2str(ii) '.dat'];
case 3
fname = ['ss ' num2str(ii) '.dat'];
end
end
Another way:
is to use the backslash character in the formatting of the filename as follows:
fstr = 'ss ';
for ii = 1:999
ns = numel(num2str(ii));
for jj = 1:ns-1
fstr = [fstr '\b'];
end
ffstr = sprintf(fstr);
fname = [ffstr num2str(ii) '.dat'];
disp(fname);
end
there are many better ways to do this though
prefix = 'SS';
for n = 1:10
if n == 10
filename = [prefix ' ' num2str(n) '.dat'];
else
filename = [prefix ' ' num2str(n) '.dat'];
end
fid = fopen(filename, 'r');
...
end

Matlab; how to extract information from a header's file (text file)

I have many text files that have 35 lines of header followed by a large matrix with data of an image (that info can be ignored and do not need to read it at the moment). I want to be able to read the header lines and extract information contained on those lines. For instance the first few lines of the header are..
File Version Number: 1.0
Date: 06/05/2015
Time: 10:33:44 AM
===========================================================
Beam Voltage (-kV) = 13.000
Filament (W) = 4.052
Cond. (-kV) = 8.885
CenterX1 (V) = 10.7
CenterY1 (V) = -45.9
Objective (%) = 71.40
OctupoleX = -0.4653
OctupoleY = -0.1914
Angle (deg) = 0.00
.
I would like to be able to open this text file and read the vulue of the day and time the file was created, filament power, the condenser voltage, the angle, etc.. and save these in variables or send them to a text box on a GUI program.
I have tried several things but since the values I want to extract some times are after a '=' or after a ':' or simply after a '' then I do not know how to approach this. Perhaps reading each line and look for a match of a word?
Any help would be much appreciated.
Thanks,
Alex
This is not particularly difficult, and one of the ways to do it would be to parse line-by-line as you suggested. Something like this:
MAX_LINES_TO_READ = 35;
fid = fopen('input.txt');
lineCount = 0;
dateString = '';
beamVoltage = 0;
while ~eof(fid)
line = fgetl(fid);
lineCount = lineCount + 1;
%//check conditions for skipping loop body
if isempty(line)
continue
elseif lineCount > MAX_LINES_TO_READ
break
end
%//find headers you are interested in
if strfind(line, 'Date')
%//find the first location of the header separator
idx = find(line, ':', 1);
%//extract substring starting from 1 char after separator
%//note: the trim is to get rid of leading/trailing whitespace
dateString = strtrim(line(idx + 1 : end));
elseif strfind(line, 'Beam Voltage')
idx = find(line, '=', 1);
beamVoltage = str2double(line(idx + 1 : end));
end
end
fclose(fid);

Matlab) what should I put more with function for, sttrep, cell?

I want to make the results like this:
phraseblanks
phrasemat = Hello and how are you?
Hi there everyone!
How is it going?
WHazzup?
Phrase 1 had 4 blanks
Phrase 2 had 3 blanks
Phrase 3 had 2 blanks
Phrase 4 had 0 blanks
New phrasemat is :
Hello&and&how&are&you?
Hi&there&everyone!
How&is&it&going?
WHazzup?
so I made script "phraseblanks.m":
phrasemat = char('Hello and how are you?', ...
'Hi there everyone!', 'How is it going?', 'WHazzup?')
[r, c] = size(phrasemat);
for i = 1:r
phrasemat_new = cell(r, c);
howmany = countblanks(phrasemat(i, :));
fprintf('Phrase %d had %d blanks\n', i, howmany);
phrasemat(i,:) = strrep(phrasemat(i,:),' ','&')
phrasemat_new{i,:} = [phrasemat(i,:)];
end
fprintf('Changing one is %s\n', eval('phrasemat_new'));
script "countblanks.m":
function num = countblanks(phrase)
% countblanks returns the # of blanks in a trimmed string
% Format: countblanks(string)
num = length(strfind(strtrim(phrase), ' '));
end
and I keep having errors.
please help me..
I modified slightly your phraseblanks.m so that it works.
phrasemat = {'Hello and how are you?', ...
'Hi there everyone!', ...
'How is it going?', ...
'WHazzup?'};
r = numel(phrasemat);
phrasemat_new = cell(1, r);
for i = 1:r
howmany = countblanks(phrasemat{i});
fprintf('Phrase %d had %d blanks\n', i, howmany);
phrasemat{i} = strrep(phrasemat{i}, ' ', '&');
phrasemat_new(i) = phrasemat(i);
end
fprintf('Changing one is %s\n', phrasemat_new{:});
Obviously it could be written in a nicer, more "matlaby-way", but I didn't want to stride too far from your original version. Also you could consider using regular expressions, since if you have to spaces next to each other and you want to treat them as one blank space.

Error while trying to open files in Matlab

My code has 2 parts. First part is an automatic file opening programmed like this :
fichierref = 'H:\MATLAB\Archive_08112012';
files = dir(fullfile(fichierref, '*.txt'));
numberOfFiles = numel(files);
delimiterIn = ' ';
headerlinesIn = 11;
for d = 1:numberOfFiles
filenames(d) = cellstr(files(d).name);
end
for i=1:numberOfFiles
data = importdata(fullfile(fichierref,filenames{i}),delimiterIn,headerlinesIn);
end
Later on, I want the user to select his files for analysis. There's a problem with this though. I typed the lines as follow :
reference = warndlg('Choose the files from which you want to know the magnetic field');
uiwait(reference);
filenames = cellstr(uigetfile('./*.txt','MultiSelect', 'on'));
numberOfFiles = numel(filenames);
delimiterIn = ' ';
headerlinesIn = 11;
It's giving me the following error, after I press OK on the prompt:
Error using cellstr (line 34)
Input must be a string.
Error in FreqVSChampB_no_spec (line 128)
filenames = cellstr(uigetfile('./*.txt','MultiSelect', 'on'));
Anyone has an idea why it's doing that?
You do not need the cellstr command for the output of uigetfile in 'MultiSelect' mode: the output is already in a cellarray form (see doc of uigetfile).

How can I load 100 files with similar names and/or string in just one step in MATLAB?

I have 100 ASCII files in my directory all named as follows:
int_001.ASC
int_002.ASC
int_003.ASC
.
.
.
int_099.ASC
int_100.ASC
I have to import them in MATLAB all with importdata, which should work as follows:
A = importdata('int_001.ASC', ' ', 9)
x = A.data(:,1)
y = A.data(:,2)
My question is: how can I avoid writing 100 times importdata? Is there a way to write the first string only and then have all data uploaded?
Thanks
fls = dir( 'int_*.ASC' );
for fi=1:numel(fls)
A{fi} = importdata( fls(fi).name, ' ', 9 );
% ...
end
UPDATE:
You may use string formatting to read the files according to their numbers:
for fi=1:100
A{fi} = importdata( sprintf('int_%03d.ASC', fi ), ' ', 9 );
% ...
end
You can use strcat function in a for loop :
for k=1:n
fileName = strcat('int_',num2str(k, '%03d'),'.ASC');
A(k) = importdata(fileName, ' ', 9);
x(k) = A(k).data(:,1);
y(k) = A(k).data(:,2);
end
If you want to take this a little overboard:
alldata = arrayfun(...
#(dirEntry)importdata(dirEntry.name, ' ', 9), ...
dir('int_*.ASC'),...
'uniformoutput',false);
This line does the following
Gets a listing of all files matching the partial filename, as an array of structures (h/t Shai)
For each element in that array, performs the importdata call from your original post.
Compiles all the outputs into a cell array.