How to save function variable to file in MATLAB - matlab

I want to make a script that saves multiple base variables from the "base name". My attempt looks like this :
function [outargs] = save_with_basename(b)
basePath = 'C:\path\';
Var1 = evalin('base', [b '_1']);
Var2 = evalin('base', [b '_2']); % .. etc
for i=1:N
save([basePath b '_' int2str(i) '.mat'], ['Var' int2str(i)]);
end
end
This saves the files but the variable saved in the file is called Var1 (see the pic.), but I want it to be called 'Foo_1' if the function was called with :
save_with_basename('Foo');
I think the second argument to save works with the function variable, so it looks like I have to change its name dynamically (which is probably not possible?) , so I wonder if there is a way I can do it.
Here is the problem :
Thanks for any help !

For the sake of everything that is holy, please do not do this.
If you really have to, please please please do not do this.
If you really really really have to want to, you indeed need to use dynamic variables (but that doesn't make much of a difference now, does it?):
for i=1:N %what's N again?
evalin('base',['Var' num2str(i) '=' b '_' num2str(i)]);
evalin('base',['save([''' basePath b '_' num2str(i) '.mat''], [''Var' num2str(i) '''])']);
end
This will essentially perform
Var1 = "b"_1; %with whatever b is
Var2 = "b"_2;
...
save(['C:\path\b_1.mat'],['Var1']); %with whatever b is
save(['C:\path\b_2.mat'],['Var2']);
in your base workspace, so it will generate the Var* variables there. Small price to pay for selling your soul to the devil. Note that I may have missed the escaping of the single quotes in the second evalin.

Related

Matlab functions not 'posting' variables to workspace

I'm using some user generated functions in MatLab. It'll be quicker if I don't post my actual code here so I'll summarize.
I have two functions. Each of them exist in their own files saved under their proper names. They can be called and work correctly. Lets say function1 is:
function [Output1] function1=(a,b)
Output1=a+b
end
function [Output2] function2=(a,Output1)
Output2=a+Output1
end
new script file
a=2;
b=3;
function1(a,b);
function2(a,Output1);
This doesn't work, because function1 isn't posting Output1 into the workspace. How do I make it do that?
Check this tutorial. This is how you are supposed to write a function.
function Output1 = function1(a, b)
Output1 = a + b;
end
Then your second function will get the input like this.
function Output2 = function2(a, Output1)
Output2 = a + Output1;
end
Of course you need to store answers of functions into variables to have them stored in the workspace.
aa=2;
bb=3;
Output11 = function1(aa,bb);
Output22 = function2(aa,Output11);
If you don't use Output11 and Output22, functions will store their result into ans variable in the workspace. And obviously, apart from the fact that you cannot pass the variable to the second function as Output1, second function will overwrite the ans.

Get acces to handles while in a Callback function

I have a Problem with my callback functions.
I wrote a small Example For it :
function drawMeAnImrect
Numbers = [1,2,3];
h = imrect();
h.addNewPositionCallback(#(h)Randomfunc(Numbers));
h.wait();
Numbers = [1,2,3,4];
end
function Randomfunc(Numbers)
disp(Numbers)
end
everytime i move the rect i will print the Numbers 1,2 and 3, even if i change the Numbers. Ist there a way to avoid this ? It works with global variables but i dont wanna use many global variables. I hope someone can help me. Thx

Create a matrix from all the variable in the workspace starting with a specified name

For example, imagine that I've in my workspace 100 variables whoes names range from var_1 to var_100. Now I want to create a matrix using all the variable starting with the name 'var_'.
I know I could try to list all the variables, but that would be ineficient and long:
A = [var_1 var_2 ... var_100]
Is there a better way to do complish this?
While this is probably (most definitely) not a good idea, here is what you can do:
varstr = 'A = ['
for ii = 1:100
varstr = [varstr, ' var_', num2str(ii)];
end
varstr = [varstr, '];']
eval(varstr)
The eval function lets you execute a string of matlab code. Therefore, you just need to generate a string that constructs the array, then pass it to eval. Fortunately, this is pretty easy:
eval([ 'A = [' sprintf('var_%d, ', 1:100) ']']);
It might be a little clearer if you actually do the assignment outside of the eval, like so
A = eval([ '[' sprintf('var_%d, ', 1:100) ']']);
Note that the string here has an extra trailing comma. That doesn't seem to be a problem, at least on 2014b.
If you don't know the total number of variables, you can get them with the who command. This returns a cell array of strings, which you'd then reformat and pass to eval, like so
my_variables = who('var_*');
% You may want to sort (re-order, take a subset of) my_variables here
str_to_run = '['
for ii=1:length(my_variables)
str_to_run = [str_to_run, my_variables{ii}, ',']
end

How to access a matrix to a m file from another m file?

Suppose the matrix is A which is in a m file new1.m . Now I want to access this matrix to another m file new2.m . How can it be done ?
Your question is a little nonspecific, but I'll try to answer.
There are several ways to do this,
Assuming that you have a m-file (script) named 'new1' with (for example) A = rand(4) in it. You could just run it in new2.m before you want to use A
new1;
B = 2*A;
Note that new1 will return all the other variables assigned in it, flooding your workspace. Perhaps not a problem, but if so, you could just clear them with
clear var1 var2 var2 etc.
Another way is to make new1 into a function and return (only) A
function A = new1()
but I'm guessing that might ruin some other purposes of new1.
In that case you could return A only if the function is called with a special input argument (for example 'getA')
function new1(varargin)
...
... % some code
...
if nargin && strcmp(varargin{1},'getA')
assignin('caller','A',A);
end
And so from new2, just call the function.
new1('getA');

Assigning to variables using dynamic naming

I am creating a function with two inputs, and would like to know how I can name the output accorinding to the name of the inputs.
E.g.
function [padded_*input_name*] = padstruct(S, F)
later in code...
else
padded_*input_name* = padarray(toPad, (longest - size(toPad,1)), NaN('double'), 'post');
So if I enter a struct (labelled as S in the input arguments) called my_struct, I would like to get an output called padded_my_struct. But this should be free to change according to the name of the input struct. I want to do this because I have a lot of structs to run through this function and I want to explicitly know from the output name, which is which.
I am a beginner with Matlab and so would appreciate any exaplanation or references to literature.
I don't quite give you what you want. Instead, I have a function that, given the inputs Account and F, produces in the base workspace a variable "padded_Account", and returns the name of the variable it creates.
function padded_Sname_str=padstruct(Sin,F)
%get the name of the structure used in the function call here
Sname=inputname(1);
%do stuff to Sin here
Sin.pad=F; %this is just my test operation
%create the name of the new variable you want
padded_Sname_str=['padded_',Sname];
%this creates it in the base workspace, since passing back as an
%output argument doesn't preserve the name
assignin('base',padded_Sname_str,Sin)
return
Hope this is helpful. Cheers!
Try this -
function [padded_*input_name*] = padstruct(S, F)
%// .. later on in code
else
value = padarray(toPad, (longest - size(toPad,1)), NaN('double'), 'post');
evalc(['padded_' inputname(1) '= value']);
Let us know if it works for you!