Calling the function doesn't work - matlab

I have a cell array of stucts, each containing the personalia of a person. I put it into this function to get them listed in a text file of a chosen name.
function store( filename, persons )
fid = fopen(filename,'w');
for i=1:length(persons)
fprintf(fid, '%s',serialize_person(persons{i}));
end
Now this function works fine: I enter a <1x3 cell> and get out a text file with three listed persons. However, I want to call this function from another:
function process_store()
list=input('Write in the list of persons you want listed: ');
fprintf('\n')
newfile=input('Give the text file a name: ','s');
store(filename,list)
end
Here I enter the name of the <1x3 cell> as before, but I get a error message "Error using input,Undefined function or variable 'persons'."
Why is this? Am I not using the exact same data as Im using in 'store'?

The problem is that the variable persons isn't accessible inside the function process_store. In Matlab (and most other programming languages) functions can't access variables defined in their calling functions. To understand this better, I recommend having a read of the Wikipedia article on levels of scope.
You essentially have two options here:
Make persons a global variable, both in your workspace and in the function process_store, by using the declaration global persons. I wouldn't recommend this.
Use the function evalin to allow process_store to access variables in its parent workspace.
I'd go with option 2 if I were you. It's a little tricky, so let me explain how it works. Let's create a variable persons in the global workspace.
>> persons = {'John', 'Jack', 'Jill'};
Now say we have the following function
function example()
x = input('Give me a variable name: ');
disp(x)
end
What happens if we try to use it?
>> example()
Give me a variable name: persons
Error using input
Undefined function of variable 'persons'
Error in example (line 2)
x = input('Give me a variable name: ');
Oh dear. That's because the function example doesn't have access to the global workspace, which is where persons is defined. But instead, we can store the name of the variable we want to access, and then check out its value in the global workspace by using evalin, like this
function example()
s = input('Give me a variable name: ', 's');
x = evalin('caller', s);
disp(x)
end
Now if we use it:
>> example()
Give me a variable name: persons
'John' 'Jack' 'Jill'
It works as we expected! Great!
Massive disclaimer
There is almost never a good reason to use functions like evalin (or eval, or assignin or any other function that messes around executing strings as code). There's almost certainly a better way of doing what you want to do. But without knowing what it is you're trying to do, it's hard to give you better advice.

At the prompt
Write in the list of persons you want listed:
if you typed
persons
then you would get exactly that error message if the variable persons was not defined.

Related

Matlab 'main' function isn't reading local functions

I have a code in matlab (~1000 lines) that constists of about 15 functions. The code runs fine with each function as a different script, but I want to put them all into one file so I can use the publish function more easily. However, when I put them all together my 'main' function isn't recognizing the local functions. Here's what it looks like:
function full_function()
...
values = fvalues(0);
...
end
function values = fvalues(state)
...
end
When I try to run it, it gives me
"Undefined function 'fvalues' for input arguments
of type 'double'.
Error in full_function (line 32)
values = fvalues(0);"
I've looked all over for how to do local functions and I have no idea what I'm doing wrong. If I right-click on fvalues and hit 'open' it even brings me to the correct portion of the code, so I have no idea why full_function cannot read it. Please help! Thanks.

Matlab Array of structures: string not working

I am reading an input from a file and importing it into my data to run in Matlab:
parts = strread(tline,'%s','delimiter',';')
employee(i).name = parts(1);
employee(i).salary= str2double(parts(2));
Then I try to print it out:
for i = 1:3
fprintf('salary: %.2f\n',employee(i).salary);
fprintf('employee name: %s\n',employee(i).name);
end
The salary prints with no problem. But the for the variable "name" it gives an error:
Error using fprintf
Function is not defined for 'cell' inputs.
fprintf('employee name: %s\n',employee(i).name);
I looked for some other examples:
access struct data (matlab)
How do I access structure fields dynamically?
Matlab Error: Function is not defined for 'cell' inputs
How do i define a structure in Matlab
But there is nothing to address this case, where only string is not working.
I have not explicitly declared the data as struct, i.e. inside the code there is nowhere the "struct" word is included, but Matlab apparently automatically understand it as an "Array of structures".
Any hints what might be missing here?
All comments are highly appreciated!
The issue is that employee(k).name is a cell (check with iscell(employee(1).name)) and the format string %s doesn't know how to handle that.
The reason that it is a cell is because strread returns a cell array. To grab an element from the result (parts), you want to use {} indexing which returns a string rather than () which will return a cell.
employee(i).name = parts{1};

A way to dynamically save files in Matlab? [duplicate]

This question already has answers here:
Dynamically Assign Variables in Matlab
(2 answers)
Closed 8 years ago.
I want to be able to save variables to disk sometimes. And I want to save it in a subfolder called '_WorkData'.
The bellow code works fine as a stand alone code
OutputName = 'my favorite file';
save(['_WorkData/' OutputName '.mat'], 'foobar');
However as a function it cant find the variable Variable 'foobar' not found.
function noDataReturn = saveFileDisk(name,variable)
save(['_WorkData/' name '.mat'], variable);
noDataReturn = 'file saved';
end
I can see why this happens but I'm not familair enough with matlab code to understand how to correct it.
Any help would be appreciated!
This is a three-fold problem.
You have to pass the variable to your function (and not the string)
However, the save call actually needs the string
The function has to have a variable with the original name to save it as intended.
Here's how it works:
function noDataReturn = saveFileDisk(name,variable)
savename = sprintf('%s',inputname(2));
S.(savename) = variable;
save(['_WorkData/' name '.mat'], '-struct', 'S', savename);
noDataReturn = 'file saved';
end
You obtain the original variable name using the inputname function (in this case, the second input is what you are after).
Next, you need to create a struct with a field name corresponding to your original variable name.
With this, you can utilize the save function's option to save fields from a struct individually.
Now, when you call
saveFileDisk('test_name',foobar)
the result will be a variable foobar in your test_name.mat-file.

Listing variables in workspace in Matlab following a certain pattern and store them in a cell array

I have 5 variables in my workspace named:
testahello
testbhello
testchello
testdhello
testehello
How can I build the cell array {'testahello'; 'testbhello'; 'testchello'; 'testdhello'; 'testehello'}?
who test*hello returns:
>> who test*hello
Your variables are:
testahello testbhello testchello testdhello testehello
But I don't know how to build a cell array from this output, or whether there exists a more suited function than who.
Use the function-form to call WHO:
>> c = who('test*hello')
c =
'testahello'
'testbhello'
'testchello'
Basically there are two ways to call functions in MATLAB, the command syntax and the function syntax. The first doesn't allow to capture return values in variables.

Matlab: How to remove the error of non-existent field

I am getting an error when running matlab code. Here I am trying to use one of the outputs of previous code as input to my new code.
??? Reference to non-existent field 'y1'.
Can anyone help me?
A good practice might be to check if the field exists before accessing it:
if isfield( s, 'y1' )
% s.y1 exists - you may access it
s.y1
else
% s.y1 does not exist - what are you going to do about it?
end
To take Edric's comment into account, another possible way is
try
% access y1
s.y1
catch em
% verify that the error indeed stems from non-existant field
if strcmp(em.identifier, 'MATLAB:nonExistentField')
fprintf(1, 'field y1 does not exist...\n');
else
throw( em ); % different error - handle by caller?
end
end
Have you used the command load to load data from file(s)?
if yes, this function overwrite your current variables, therefore, they become non-existent, so when you call, it instead of using:
load ('filename');
use:
f=load ('filename');
now, to refer to any variable inside the loaded file use f.varname, for
example if there is a network called net saved within the loaded data you may use it like:
a = f.net(fv);
I would first explain my situation and then give the solution.
I first save a variable op, it is a struct , its name is coef.mat;
I load this variable using coef = load( file_path, '-mat');
In a new function, I pass variable coef to it as a parameter, at here, the error Reference to non-existent field pops out.
My solution:
Just replace coef with coef.op, then pass it to the function, it will work.
So, I think the reason behind is that: the struct was saved as a variable, when you use load and want to acess the origin variable, you need point it out directly using dot(.) operation, you can directly open the variable in Matlab workspace and find out what it wraps inside the variable.
In your case, if your the outputs of previous code is a struct(It's my guess, but you haven't pointed out) and you saved it as MyStruct, you load it as MyInput = load(MyStruct), then when use it as function's parameter, it should be MyInput.y1.
Hops it would work!
At first load it on command window and observe the workspace window. You can see the structure name. It will work by accessing structure name. Example:
lm=load('data.mat');
disp(lm.SAMPLE.X);
Here SAMPLE is the structure name and X is a member of the structure