Open file local to function file in Octave - matlab

I'm trying to get a MATLAB project work under Octave. The project's layout looks like this:
/myproject/funcs/f1.m
/data.csv
/examples/test.m
I want to run the routine test.m, which makes use of the function f1. Inside f1.m, there's a call to open the data file:
[...]
data = dlmread('data.csv'); % Read the csv file
[...]
When I'm inside the examples directory, this fails:
error: dlmread: unable to open file 'data.csv'
So I guess what I'm looking for is some way to tell Octave that the file data.csv is in the same directory as the function definition trying to open it. This solution should be MATLAB-compatible, so I can contribute the changes necessary to make it work under Octave back to the project.
What I already tried:
data = dlmread('./data.csv'); -> the same error as before

Related

How to load .mat files onto Matlab? Basically what's wrong with my code?

For this project we have been given code, and will be changing some inputs and assumptions. Thus, I already possess the original codes, but just changing all the creator's file paths to match my own computer is yielding me a lot of trouble. The following, and many variations of, continually yield errors.
load \Users\myname\Library\Documents\...
The error is
Error using load
'Unable to read file
\Users\myname\Library\Documents...'.
No such file or directory.
My files are stored in my Documents. Another person in my group on windows has used
load C:\Users\hisname\Desktop\...
Is there something I'm missing in my line, similar to the C drive but on Mac? Is my code just completely wrong, I'm able to load files in R quite easily, but Matlab is posing a huge hurdle. I have no experience with Matlab and have been asked simply to run this code.
On the Mac, path components are separated by /, not \. Thus, you should type
load /Users/myname/Documents/filename.mat
You can use the location bar at the top of the command window to change to the directory where your file is located, and then you can type
load filename
to load filename.mat.
Also, are you sure you have a Documents directory under Library? Why?
To run code from a file called "my_file.m", than just open your Matlab and type run my_file.m. This will run your script in the Command Window.
The load function is used, if you want to load a .mat file. These are normally files, where variables from your workspace are stored.

Save workspace of unknown workspace in Matlab

Is it possible to save workspace variables from a function that I am calling and cannot explicitly edit without file I/O?
I know I can use the save function to save all of the variable names in a workspace, but what if I wanted to save the workspace variables from a function that I am calling, like a built in function (mean, sum, etc).
I would like to save all of the variables from a function's workspace before it returns back to the function I am writing, and I would like to do it without opening the file each time and adding an extra line of code; is this possible?
In case anyone is interested:
I have yet to find a solution to the exact question I asked, but I found a solution that works well enough with a little extra file tracking.
Using the function onCleanup, you can specify that all the variables be saved right before the function returns to the caller. Using this and a little file parsing, you can open the code in question as a simple text file, and insert the onCleanup code anywhere in the file (easier than inserting save as the last line). Then, you can run the code and track the new .mat file using the previous file name or any naming method you choose.
That will enable you to save all the variables in a workspace just before the function exits, but it does require file parsing, see simple example below:
readFile = fopen('filename.m');
writeFile = fopen(['filename_new.m']);
%Ignore the first line (hopefully the function header, may need extra parsing if not)
functionHeader = fgets(readFile);
%Print the function header
fprintf(writeFile,functionHeader);
%Print the clean-up code
%NOTE: This can go anywhere in the file
fprintf(writeFile,sprintf('onCleanup(#()save(''%s.mat''))\n',filename)));
nextLine = fgets(readFile);
while ischar(nextLine)
fprintf(writeFile,nextLine);
nextLine = fgets(readFile);
end
With the above, a new file is created (filename_new.m) which needs to be run, and will create a mat file (filename.mat) with all of the workspace variables in it.
eval(newFileName(1:end-2));
Now, by tracking the .mat file, you can do whatever is necessary after this point. For my purposes, I was interested in the memory used by the said function, which is available by accessing the mat object of the .mat file.
matObj = matfile('filename.mat');
stats = whos(matObj);
fileSize = sum([stats.bytes]);
Try the "save" function.
Add this line in your called function:
save('filename')
Here is my sample code:
a=10; b=6;
c=addition(a,b);
And the function is defined as:
function [out]=addition(a,b)
out=a+b;
temp1=a;
temp2=b;
temp3=a-b;
save('C:\data.mat');
end

Save or Load Data from/to GUIDE/Workspace

I'm new in GUIDE in MATLAB. I have two different problems:
I would like to save in a .mat file all variables (about 1000) from workspace using a button in GUI in MATLAB. How can I do?
I have a button where after press on it I'm able to load a specific .mat file from my path, always using GUI, but I would like that the variables contained in this file, became presents in the base workspace.
In other words, I have a button, "LOAD", in GUIDE in MATLAB where I can load a .mat file, and the variables contained in the .mat file must be loaded into the 'base' workspace when the button is clicked.
Please help me.
For your first question, I would suggest just putting a command like save('filename.mat'); in the "Save" button's callback. But what variables? If they are in the base workspace, see my answer to your second question below.
To load data into the base workspace, you might try the evalin command:
evalin('base','load(''filename.mat'')');
The 'base' argument tells it to run the command in the base workspace.
If your file name is in a variable:
fname = 'filename.mat';
evalin('base',['load(''' fname ''')']);
Alternatively, you could use sprintf:
loadCmd = sprintf('load(''%s'')',fname);
evalin('base',loadCmd);

octave load function

i'm trying to load a mat file from a subdirectory using the following code:
% filename_str is read from a text file
directoryname_str = "./data";
f = fullfile(directoryname_str, filename_str);
load(f);
when i run this sequence, load says it can't find the file...but when i copy or type the relative path and the file name by hand into an active octave session, everything works like a champ with no errors.
i assume this has something to do with how octave searches for mat files? if so, what's the correct environment variable or function call i need to make in order for this code to work?
thanks!
Are you sure that what you put into the variable f is the same as what you input manually in octave?
Are you also in the same directory? Because you're specifying relative paths, this should be the case.. you can get the current directory octave is in with pwd
And last of all, you can double check file existence in octave itself using exist
exist(f,'file')
If this returns false, there's definitely something wrong with your current directory, are something's very weird going on..

How to open a file that is already open with fileshare permissions

I'm trying overwrite a csv file that already exists in Matlab on Windows. The problem is sometimes I have the file open in Excel. When this is the case, the write operation fails.
Is there anyway to overwrite the file in Matlab? I do NOT want to use ActiveX to connect to the Excel session and edit the file that way.
Seeing this post about FileShare settings made me think it might be possible, but none of the fopen parameters seem to be able to do the trick. Excel may be locking the file with exclusive write access, in which case there is no getting around it. Does anyone know how to check this?
Example of problem:
% make csv file
x = magic(4);
csvwrite('foo.csv', x);
% open foo.csv in EXCEL
% try writing again
csvwrite('foo.csv', x); % cannot write a new file
[fid, msg] = fopen('foo.csv' ,'w'); % cannot open handle for writing
As a side note, I used to be able to overwrite a file open in Excel when the file existed on a Linux box, and I had the file open over the network on a Windows box.
Those FileShare settings are for files opened from the Win32 API's CreateFile family of functions, not the C style fopen family, which Matlab exposes. The fopen options won't get you there. See http://support.microsoft.com/kb/99173 for a quick rundown of the differences. (If you really wanted to use CreateFile or other Win32 I/O, e.g. to check to see if Excel has the file locked or lock it yourself, you could call it from Matlab through .NET using System.IO.File.)
Regardless, by default, Excel opens the file in write mode, and gets an exclusive (write) lock. So you couldn't open it for writing anyway, those file sharing settings would only let you open the file for reading. If you want to be able to overwrite an Excel file while it's open in Excel, you need to have Excel open it in read-only mode like katrasnikj suggests. This causes Excel to read it in to memory once and then release the filehandle.
Try turning on the Read-Only file attribute on these files after you write them by shelling out to the attrib command. This will cause Excel to open them read-only by default. Then clear the read-only attribute right before opening it from Matlab for rewriting.
if exist(file, 'file')
[status,result] = system(sprintf('attrib -R "%s"', file));
end
[fid,msg] = fopen(file, 'w');
% ... write the file and close it ...
[status,result] = system(sprintf('attrib +R "%s"', file));
There's still a race condition between reader and writer, but if you write the file fast, it'll be a short window. Better would be to write out the csv to a temp file in the same directory, and then just turn off the read-only attribute long enough to swap the new file in to place with a movefile or java.io.File.renameTo. Still a race, but probably good enough to use in practice.
You could also change the permissions on the directory the files are in so your writer process has Modify permissions but the users running Excel only have Read access. Then the Excels will always open read-only and you don't have to fiddle with file attribs.