How to pass file names to MATLAB? - file

In the directory that I am working, I have many files file1 file2 file3 etc. I don't know the names of the files in advance, however I know that they are the only files starts with A , for example A*.txt. How can I pass file names in an array to MATLAB?

Just use
files=dir('./A*.txt')
files is a structure, so you can acces the filenames with
files(Index).name
If you want all the filenames in an easy-to-use cellarray, try
cellarray = {files(:).name}

Here's a short and simple answer:
filenames = dir('A*')
This assumes you want to return files in the present directory beginning with "A", you could build off this example as needed though.

Your question is a bit broad, so I'll make a few assumptions, namely that you don't mind cell arrays and that the files are of a specific extension. With that said, if you want to do it in a general manner and you know the extension, you can do:
EDIT: in light of the fact that you know the first part of the filename, you can modify your call to the dir function reflect that:
%have the part of the filename you know here, in your question that being 'A'
file_prefix = 'A';
file_path = pwd;
%this will get all of the .txt files. Put the extension you want here
file_names = dir(strcat(file_path,filesep,file_prefix,'*.txt'));
fnames = cell(length(file_names), 1);
for i=1:length(file_names)
fnames{i} = file_names(i).name;
end
This will give a cell array of strings containing all of the filenames of the specified extension, which you can pass to whatever needs the filenames. You can generalize this to get the file names from any directory by specifying the path (instead of using pwd, which gets the contents of the current directory)

Related

I want to replace a lot of files with differing names with the same file without changing the name, how can I do that?

I have a bunch of .txd and .dff files that have different names, let's say, like, img1 img30 greenimg3, etc. all in the same folder. I can compile a list of these names that I want to replace (but not all the files in the folder will be replaced), but how can I replace my list of files with just one file without altering the name of the file? So it remains img1, img30, greenimg3, etcetera but with the replaced file. I hope this makes sense. I would be grateful if someone could write something that I could use, as I don't know how to code myself.
not sure if i understand corretly, but you could do this in python:
import os
folder_path = "./folder"
with open("source.file", "rb") as source_file:
source_file_content = source_file.read()
for file in os.listdir(folder_path):
with open(os.path.join(folder_path, file), "wb") as destination_file:
destination_file.write(source_file_content)
where "./folder" is the path to your folder containing all files you want to overwrite and "source.file" is the path to your file you want to overwrite with.
this script reads and writes the files as binary

Is it possible to use an output name created within RMD chunk as knit file destination?

I am knitting markdown code initiated from a database command button with a shell command to execute a batch file. The goal here is to knit the file into a directory specific to the database record. Batch file execution currently looks like this:
"Rscript.exe" -e "library('knitr'); rmarkdown::render('MyCode.Rmd', output_file="MyRMD.html")"
Inside the rmd file I create a variable (say 'out_dir') that contains the directory string where I want the output file to be stored. Is there any way I can use this variable to direct where knitr will store the rendered file? Other than YAML parameters, can you control knitr output options from within the code?
This wasn't the approach I was trying to accomplish, but the workaround was to build a front end script to the markdown document that did the necessary pre-processing and then passed the values using "output_file", "output_dir" and a "params()" list matching the YAML header in the rmd (Note this part is not necessary in solving the original question, but since I took this approach it makes it handy to pull even more pre-processing code out of the rmd and into the front end passing values through params). So the front end initiates the knit:
rmarkdown::render("MyCode.Rmd",
params = list(P1 = p1, P2 = p2),
output_file = 'MyRMD.html',
output_dir = 'Dir_From_Database_Record')
And just for completeness the markdown rmd YAML header from MyCode.RMD looks like:
output: html_document
params:
P1: NA
P2: NA

Trying to loop through Directory to list all the files using lua

I am new to lua to trying to understand and put pieces to together and looking out for some help.
I have gone through the existing articles on lua file looping but unable to get the desired output.
Question - I have a folder with files, Folder path - "D:\Test_Files\Outbound\Client\final"
Files in the folder with extension - .txt
Trying to :
Get the count of files in the folder(in this case "final" folder).
Read every file, building a loop something similar to this:
list = {}
for i=0,(#Totalfilecount) do
local fr = io.open('D:\Test_Files\Outbound\Client\final\'..filename.,'rb')
local f = fr.read('*.txt')
Customfunction(f) -- Passing file content to customfunction to apply business logic.
end
Questions :
How to get file count from a directory?
How to read the directory to check if the files with "*.txt" exist?
How to use table list to store each file name and read through the loop?
How to read each file via loop and pass the value to function "Customfunction(f)"?
Code is expected to run on windows. Please share suggestions in pure lua without using external file system functions such as 'lfs' as we do not like to import external functions.
Any Suggestions/help will be greatly appreciated!
You can't (at least shouldn't) do this without extensions to Lua. To accomplish this, you have to download LuaFileSystem library. You can do it using LuaRocks:
$ luarocks install luafilesystem
Use library as such:
require "lfs"
function dirtree(dir)
assert(dir and dir ~= "", "Please pass directory parameter")
if string.sub(dir, -1) == "/" then
dir=string.sub(dir, 1, -2)
end
local function yieldtree(dir)
for entry in lfs.dir(dir) do
if entry ~= "." and entry ~= ".." then
entry=dir.."/"..entry
local attr=lfs.attributes(entry)
coroutine.yield(entry,attr)
if attr.mode == "directory" then
yieldtree(entry)
end
end
end
end
return coroutine.wrap(function() yieldtree(dir) end)
end
An example use of code above:
for filename, attr in dirtree("D:\Test_Files\Outbound\Client\final") do
print(attr.mode, filename)
end
You have to check does extension equal to txt. To read file extension use this snippet:
function GetFileExtension(path)
return path:match("^.+(%..+)$")
end
So, to answer your question(s), you can get amount of files in directory just by counting elements in array returned in dirtree. To answer second question, just use code from the post. Table that you want is returned by dirtree(), but you may want to extract only .txt files from it. To read a file, just check other SO answers. You've got given name (in array), so use it.
EDIT: You can parse result of dir and ls command to get directory listing, but you shouldnt. Althrough this way you wouldn't need to install any libraries, your code is going to be heavily OS-depedent.
Adding libraries to your code isn't so bad. Hacking things is worse.
(Not sure file extension extracting function is going to work. I didn't make dirtree code used in this post, it belongs to David Kastrup)

Get Names of Subdirectories within a Directory

I am trying to write a Visual Basic program that gets the names of all subdirectories within a directory, writes them into an array, and then writes the contents of the array to a dat file. I am however having a problem with the arrays not filling up with the directory names. Here's a piece of my code below.
For Each directoryName As String In IO.Directory.GetDirectories(appdata)
allAppdataDirectories(appdataNameId) = Dir(appdata)
appdataNameId += 1
ReDim Preserve allAppdataDirectories(appdataNameId)
Next
The above code snippet is supposed to get all of the directory names within my appdata folder. Assuming variable and array in this code has been declared already, what is wrong with it? I know that writing to the data file is working because I have done it in another context in this program and it works just fine.
You are not using the directoryName variable
Maybe it also would be easiest to use a list insted of an array
Check if this solution can work for you :
Dim allAppDataDirectories As New List(Of String)
For Each directoryName As String In IO.Directory.GetDirectories(appData)
allAppDataDirectories.Add(directoryName)
Next
'Finally, if you need an array you can use allAppDataDirectories.ToArray()

Matlab's 'save' function - how to name the variable inside the .mat file same as file name?

I want to save the result of the q for each case_no in corresponding string of the q_cases as a .mat file. With my statement of save(q_cases{case_no},'q') even though the names of files are coming as the corresponding string of q_cases, however all those .mat files contain variable with the same name of q. When I open those .mat files I get a variable with name q for all the 3 files. However, I want the names of the variables stored in those files same as the name of the files i.e. q_a, q_b and q_c respectively.
One way to solve this is to assign the variable name with eval.
EDIT
Eval is usually not recommended, since it is difficult to debug/maintain. Thus, you can instead create a structure first and use the -struct-option of save, like this:
for case_no=1:length(n)
[q,S]=q_from_A(nModel,nModel_want,nCell,T,A{case_no},B{case_no},C{case_no},D{case_no},E{case_no},F{case_no});
%# create structure for saving
saveStruct = struct(q_cases{case_no},q,...
S_cases{case_no},S);
%# ... and save it
save(q_cases{case_no},'-struct','saveStruct',q_cases{case_no});
save(S_cases{case_no},'-struct','saveStruct',S_cases{case_no});
end

Resources