Matlab: Saving plot images, override plot.m - matlab

Working on MATLAB 2008, I am trying to save all the images my scripts produce when invoking the "plot" function.
In order to achieve this, I have two possible solutions:
Either I write another function having the same parameters and perform a search/replace in the *.m sources
or I override the plot.m file so that I write the image into a specific directory when generated.
I did many searches and I am unable to find the plot.m source file. The only file I found is located in the toolbox directory and does not contain any code (except some commented documentation).

you can simply use the print command and save them into a directory that you can also make using the mkdir command.
Sample code
clc; close all; clear all;
x = 1:10;
y = x.^2;
plot(x,y)
if exist('plots','dir') ~= 7
mkdir('plots'); % make directory if it does not exist
end
print -dpdf ./plots/jawn.pdf
Read the print documentation, to learn how to print in other file formats
Also, I would not suggest overriding the plot command, and you will likely not be able to find the source code for plot.m because that is proprietary MATLAB code

Related

Default "legend" function overwritten by accident

I am using the BNT-toolbox, a big library written in matlab for inference in bayesian networks.
I had to add this toolbox to the path of MATLAB. But after doing that I can't use the default legend function any more.
I think that this library might have his own legend function, overwriting the default one. How can I manually tell MATLAB that I want the original one and not the one in the new toolbox?
Tried in Matlab 2018b and 2020a
EDIT: to reproduce it:
When I run the testscript, it shows the lines and the legend.
https://github.com/bayesnet/bnt, this is the toolbox I talked about. I downloaded it, unzipped and then added it to my path with Home -> Set path -> add folder with subfolder
When I run the script now, it shows the lines and not the legend.
NOTE: when I tried another way of plotting (see testscript 2), the legend shows itself again. So this is a working "workaround"
Testscript1: (location: C:\Users\TomDe\Downloads\FullBNT-1.0.7\bnt\own\testscript1.m)
x = linspace(0,pi);
y1 = cos(x);
plot(x,y1)
hold on
y2 = cos(2*x);
plot(x,y2)
legend('cos(x)','cos(2x)')
Testscript2
% Some other code
tiledlayout(2,1)
nexttile
plot(inputPath)
hold on
plot(sensorPath)
plot(inputInference)
hold off
title('The Input sequence and sensor readings ')
legend('Path', 'sensor', 'Inference')
You can check that that is indeed the case with the which function:
>> which legend -all
It's generally a bad idea to overshadow MATLAB's own functions. I highly suggest you avoid this problem in the first place. Create a MATLAB package and place the source code of this toolbox in there.
For demonstration purposes only, I'll show how to call the real legend.m:
>> wd = pwd;
>> cd 'C:\Program Files\MATLAB\R2020a\toolbox\matlab\scribe\'
>> legend(...)
>> cd(wd);
this being the location of the file on a MATLAB R2020a install.
There are two things you can do:
You always want to use the default legend, never the one in the toolbox: use the -end option to your addpath call when adding the BNT toolbox directory, so that its functions appear at the end of the path. MATLAB will always find functions by looking through the path directories in turn, the directories earlier in the path therefore have precedence.
You want to use both versions of legend, and want to choose which one to use: write a little support function that removes the BTN toolbox from your path, calls legend, then adds the toolbox back in. Such a function looks like this (save it as original_legend.m somewhere in your path, then use it in the same way you'd call legend but using this new name instead):
function out = original_legend(varargin)
rmpath /path/to/bnt/toolbox
out = legend(varargin{:});
addpath /path/to/bnt/toolbox

detect whether .m file is matlab or mathematica

I have been editing Matlab script in Vim for some time now. Recently I started taking an interest in moving my Mathematica work to plain text files so they can be managed using git and edited using Vim. Unfortunately Mathematica also uses the .m extension for its package files and is therefore not easily distinguished from Matlab scripts. Since I would like my editor to do the work for me I was wondering if anyone has come up with an idea for identifying both based on the contents of the file. I would be fine with something that works in most cases, but am reluctant to use a solution that requires alterations in the scripts such as adding a comment.
A ".mat" or ".m" file created with MATLAB's save() function will always start with the plain text identifier "MATLAB". So, using MATLAB syntax, you might do this:
% Set up a workspace variable and save to file
tmp = 1:10;
save('test.m');
% Open the file, read the first line and close again
fid=fopen('test.m');
firstline=fgetl(fid);
fclose(fid);
% Branch depending on file format
if ((numel(firstline) >= 6) && strcmp(firstline(1:6), 'MATLAB'))
disp('This may well be a MATLAB file.');
else
disp('This is probably not a MATLAB file.');
end

matlab figure taking too long to open

I want to save a plot in .fig extension. I tried many ways but it takes too long to open (in fact it never opens sometimes after infinite wait time). I had to use Ctrl C in the command prompt to stop it.
Here are my commands to print a figure in fig format
saveas(h,[path FolderName FigureName, '.fig'])
where h is the handler. I used h at many places in the code file
(where the variables inputsAxis etc.., are defined basing on the where I need to plot. plot count is set to 10, inputsAxis = [1,2],SignalAxis = [3 4], VoterOutAxis -= 5 )
h(1) = subplot(plotCount,1,inputsAxis);
h(2) = subplot(plotCount,1,SignalAxis);
h(7) = subplot(plotCount,1,voterOutAxis);
h(5) = subplot(plotCount,1,FlagAxis);
h(6) = subplot(plotCount,1,MarginAxis);
h(9) = subplot(plotCount,1,flagAxis,'Color',[1 1 0]);
Also used
savefig([Path FolderName FigureName '.fig'])
I can print in the jpeg file but it is not as good as .fig for the simulation I am running.
I am not sure what I am missing here. It is more useful to me saving the figure in .fig format but when I do I can not open it by double clicking on it or by using openfig(filename) command.
Following our discussion in your comments section, my suggestion is to save your variables into a .mat file, which is very fast.
For example, if you want to save specific variable a, simply enter
a=3;
save('variables.mat', 'a');
clear all;
load('variables.mat');
Alternatively, if you simply want to save all variables into a .mat file, enter
save('allMyVariables.mat');
clear all;
load('allMyVariables.mat');
Please note that I wrote clear all to indicate that you may overwrite variables between save and load, or that you may even restart Matlab completely.
Check out http://www.mathworks.com/help/matlab/ref/save.html?refresh=true for a detailed explanation.
Cheers

Passing variables between m files and gui in matlab

I have matlab scripts(m files) now I have to
1. integrate them to a GUI using the guide tool. there is an initialization file say 'file1' and dependent files 'file2','file3' etc. have to push this into GUI.
2. The figure/image plotting is causing me issues i.e. I have 2 different axes plots and have to push images from say file2 to axes1 and file3 to axes2 but it is plotting on the same axes time and again.
Note: file2 and file3 have two different calls from gui using the pushbutton but file2 is dependent on file1 and file3 on file1 and file2
Need help to proceed
Thanks in advance
Set-up figures in initialisation script
hFigures(1) = figure;
plot((1:10).^2)
hFigures(2) = figure;
plot(1:100);
Plot to a specific figure from another script
set(0,'CurrentFigure', hFigures(1));
hold on
plot(ones(10,1)*50,'r')
If you need to plot from within the GUI, you'll need to first get access to the hFigures variable (from the workspace). You can do this with:
hFigures = evalin('base','hFigures')
As I said in the comment, it would be better it you could change your scripts to functions rather than relying on workspace variables and had the initialisation function return the figure handles and the update function take figure handle(s) as parameters but I don't know much about your code base so this may not be easy to do at this stage.

Saving data to file in different path in Matlab

I am trying to save some data from current workspace in Matlab to a different folder. I tried using
save('c:\stp\vtp\train.txt','data','-ASCII');
where data is a double matrix. It gives me error message
??? Error using ==> save
Unable to write file c:\stp\vtp\train.txt: No such file
or directory.
I tried using fullfile syntax, even then it is the same case. My current working folder is in different path.
You probably need to run mkdir first. For example:
%Some data to save
x = 1;
%Try to save it in a deep, non-existent directory
save(fullfile(tempdir,'sub1','sub2','sub3','sub4','data.mat'),'x');
% This will probably recreate your error
%To fix, first create the directory
mkdir(fullfile(tempdir,'sub1','sub2','sub3','sub4'))
%Now save works
save(fullfile(tempdir,'sub1','sub2','sub3','sub4','data.mat'),'x') %No error