Octave: Problems with load - matlab

I'm currently doing a program in Octave where I want the user to be able to insert the file that he wants to load. The files in question are .mat files and are loaded with
load ("filename.mat")
I was thinking about doing something like this:
file=input("Whats the file name: ")
load ("file")
But that didn't work...
Anyone got any tips?

That's likely because you need to input the file name enclosed in single quotation marks : 'filename'. (Note: I use MATLAB but that should work just the same in Octave).
As an alternative you can use inputdlg to request user input. It gives you much flexibility as you can add fields to the prompt such as the file extension or else.
Here is a simple example:
clear
clc
prompt = {'Enter file name'};
dlg_title = 'Input';
num_lines = 1;
def = {'Dummy file'};
answer = inputdlg(prompt,dlg_title,num_lines,def)
The prompt looks like this:
You can fetch the asnwer like so:
name = answer{1};
And finally add the extension to load the .mat file:
filename = strcat(name,'.mat')
S = load(filename)
To do it in one go with the file extension:
prompt = {'Enter file name'; 'Enter file extension'};
dlg_title = 'Input';
num_lines = 1;
def = {'Dummy file'; '.mat'};
answer = inputdlg(prompt,dlg_title,num_lines,def)
name = answer{1};
extension = answer{2};
filename = strcat(name,extension)
S = load(filename)
Hope that helps!

I used Benoit_11's method but changed it to input instead since inputdlg doesn't seem to work in Octave.
clear
clc
name=input('Enter the file name, without the file extension: ','s')
filename = strcat(name,'.mat')
S = load(filename)

Related

Check wav file exists in Matlab folder

I need to check whether a wav file in Matlab work folder exists ou not. If it does, I need to load the file into a variable (file in my case), i use this code but it doesn't work.
if strcmp(file,'\n')==0
file='test.wav';
elseif findstr(file,'.')==''
file=strcat(file,'.wav');
end
[TestWave,Fs] = audioread(file);
You don't say if you are trying to find a particular .WAV file, or just any .WAV file...
If you just want to know if a particular file (of any kind) exists, use the exist() function. It returns value 2 if a file exits:
myFileName = 'test.wav';
myDirectory = 'c:\temp';
filepath = fullfile(myFileName,myDirectory);
if exist(filepath,'file') == 2
[TestWave,Fs] = audioread(file);
end
Otherwise, just search for the files you need using dir():
myDirectory = 'c:\temp';
wildcard = '*.wav';
theseFiles = dir(fullfile(myDirectory,wildcard));
for i = 1:length(theseFiles)
thisFilePath = fullfile(myDirectory,theseFiles(i).name);
[TestWave,Fs] = audioread(thisFilePath); % Load this file
% Do something with the loaded file...
end

MATLAB dir command not working properly

I have a folder containing 9 .htk files. I need to use "dir", and then "readhtk" in a loop to import them to MATLAB, but DIR appears to give 10 files instead of 9! here is my code:
htkfiles = dir('/Users/Desktop/Acsegment/mfcdir/*.htk');
nhtkfiles = length(htkfiles); % 10!!! It should be 9 tough!
data = cell(nhtkfiles,2);
for k = 1:nhtkfiles
b(k,1) = strcat({'/Users/Desktop/Acsegment/mfcdir/'},{htkfiles(k,1).name});
eval(['data{k,1} = readhtk(b{k,1});']);
end
When looking at the filenames in htkfiles, I have them like this:
htkfiles(1,1).name = '.htk'
htkfiles(2,1).name = 'fadg0_si1279.htk'
htkfiles(3,1).name = 'fadg0_si1909.htk'
htkfiles(4,1).name = 'fadg0_si649.htk'
htkfiles(5,1).name = 'fadg0_sx109.htk'
htkfiles(6,1).name = 'fadg0_sx19.htk'
htkfiles(7,1).name = 'fadg0_sx199.htk'
htkfiles(8,1).name = 'fadg0_sx289.htk'
htkfiles(9,1).name = 'fadg0_sx379.htk'
htkfiles(10,1).name = 'faks0_si943.htk'
Comparing to what I see in that folder, the first file is not supposed to be there! Anyone got any ideas why Im getting one extra file?
As mentioned in the comments: the dir command actually works properly, there just happens to be a hidden file.
These files starting with a dot could be removed from your list like so:
d=dir;
d(strncmp({d.name},'.',1))=[];

Extract value MATLAB

I need to extract the first value of the following code:
3.43099,70.8539,91.701,FAIL
The file has the '.sol' extension, but it can be read in notepad or Matlab.
I just want to know how to to read in all *.sol files in a folder and how to write the extracted value in a text file.
Thanks a lot, i would be grateful.
NEW
ita='"';
for i=1:size(z,2)
word_to_replace=input('Replace? ','s');
tik=input('Replacement? ','s');
coluna=input('Column? ');
files = dir('*.txt');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
fh = fopen(files(i).name,'w');
val=num2str(z(i,coluna));
word_replacement=strcat(tik,val,ita);
contents = regexprep(contents,'word_to_replace','word_replacement');
fprintf(fh,contents); % write "replaced" string to file
fclose(fh) % close out file
end
end
end
Many thanks
File extension does not make a difference as to what MATLAB can "read", use the fileread command to load in the file and parse its contents. You can then split on commas, since it looks like it is comma separated
files = dir('*.sol');
fh = fopen('outFile.txt','w');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
parts = regexp(contents,',','Split');
fprintf(fh,[parts{1},'\n']);
end
end
fclose(fh)
This should do what you want. It will find all files in the current directory with the .sol extension, loop through all of them, grab the first value, and write it out to a text file.
Find and replace
Finding and replacing is relatively simple as well. You can do the same looping, read the file contents, run a replacement, and then rewrite that out to the same file.
files = dir('*.sol');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
fh = fopen(files(i).name,'w'); % open handle to same file just read for overwriting
contents = regexprep(contents,'toReplace','replacement'); % do string replacement
fprintf(fh,contents); % write "replaced" string to file
fclose(fh) % close out file
end
end

Save data as modified input file name

I have a program that loads data from a .txt file and performs some curve fitting. The input file name for this example is experiment09.txt.
After processing I want to save a variable with the same input filename but appended with something like _fit. So my saved workspace variable in this case would be experiment09_fit.txt.
I have gotten this far in MATLAB:
buf = length(filename)
saveName = filename(1:buf-7)
which gives me a saveName of experiment09 but I am at a loss as to how to add my chosen string on the end to make it experiment09_fit. Once I have a valid save name I will then just call
save(saveName, 'fittedValue', '-ASCII');
Help would be greatly appreciated.
What about this:
filename = 'experiment09.txt';
[pathstr, basename, ext] = fileparts(filename);
outname = [basename, '_fit', ext]; % will give 'experiment09_fit.txt'
Also use string concatenation for adding additional names to string variables.
For example,
filename = 'experiment09.txt';
[pathstr, name, ext] = fileparts(filename);
outputName1 = strcat(name,'_fit.');
outputName = strcat(outputName1,ext);

Saving file with part of file name and date

Hi there I'm currently trying to find a way to save 2 variables from my workspace into a file. I want the file name to be put together using the original and the current date.
I only want the max value from the variables so:
max(streaking)
and
max(tap_total)
The original file name is:
3_FM001_02_05460$BandP$64_24000_FWD_1x1_PRI_PRI_PRI_PRI_15_17_ActivePixelMeans.csv
The only portion of this original file name that I would like to use is:
3_FM001_02_05460$BandP$64_24000_FWD_1x1
These can be saved in a text file or spreadsheet, it doesnt matter.
An example of the new file name would be something like this:
3_FM001_02_05460$BandP$64_24000_FWD_1x1_7-26-2012
Also,
If something could be done in the file to display which variable is which, for example:
Streaking: 1.272 % this would come from the variable max(streaking)
Tap_Total: 2.252 % this would come from the varaible max(tap_total)
EDIT:
% Construct a questdlg with three options
choice = questdlg('Would you like to save?', ...
'Save Options', ...
'Yes','No','Cancel','Cancel');
% Handle response
switch choice
case 'Yes'
disp([choice ' processing.'])
save_option = 1;
case 'No'
disp([choice ' processing.'])
save_option = 0;
case 'Cancel'
disp('Canceled.')
save_option = 2;
end
file_to_get = evalin( 'base', 'file_to_get' );
streaking = evalin( 'base', 'streaking' );
tap_total = evalin( 'base', 'tap_total' );
if save_option == 0
elseif save_option == 1
max_streak = max(streaking);
max_tap = max(tap_total);
str_streak = mat2str(max_streak);
str_tap = mat2str(max_tap);
fname = file_to_get;
pruned_fname = regexprep(fname,'_PRI(\w*).(\w*)','');
new_fname = [pruned_fname '_' date '.csv'];
path1 = '\\pfile01thn\bbruffey$\My Documents\analysis data\Banding and Streaking Results';
fid = fopen([path1 new_fname], 'w');
fprintf(fid,['Max Banding: %s\nMax Streaking: %s'],str_tap,str_streak)
fclose(fid);
elseif save_option == 2
end
This would be a great place to use the regexprep command to prune the original filename down.
Example:
fname = '3_FM001_02_05460$BandP$64_24000_FWD_1x1_PRI_PRI_PRI_PRI_15_17_ActivePixelMeans.csv';
pruned_fname = regexprep(fname,'_PRI(\w*).(\w*)','');
pruned_fname =
3_FM001_02_05460$BandP$64_24000_FWD_1x1
Now, a note about the regexprep command I used here. This is specific for the filename you provided here. Since it looks like you want to trim off everything after the the first _PRI I used a tag (\w*) which means any combination of [a-z A-Z _ 0-9] can follow. Notice that since this is a filename there is a . there hence why I added a period in and followed that with another (\w*) to finish out the csv. You can find more info on these sorts of operators here.
Now that you have the pruned_fname you can simply add whatever you want to it. So if you want to add the date in with an underscore to space it just simply do something like this:
new_fname = [pruned_fname '_' date '.csv'];
new_fname =
3_FM001_02_05460$BandP$64_24000_FWD_1x1csv_26-Jul-2012.csv
Now you simply need to open the file to write to it. you might need to append the path to where you want to save it, I'm just going to call it path for now. It would be something like C:\Documents\
fid = fopen([path new_fname], 'w')
Now with the fid you have the id of the file you want to write to. This should be a new file and if it isn't you are going to overwrite the file contents if you do it this way. Just be aware =)
Next you can simply write those first two lines to the file using fwrite fprintf, just to name a few possible functions.
Hopefully that'll get you setup there!