Why is this error happening: Index exceeds matrix dimensions - matlab

I am running a GUI system in MATLAB and I am a beginner with working with GUI's.
The code is extensively long and so I am going to just put in what and where I have things and see if it is enough information for help to be given, thanks.
in my first GUi I have this in the opening function:
HW12_result_bhanford(handles.scan_age, handles.check_athlete, handles.radio_male, handles.radio_female)
this is supposed to be transferring these four variables over to my third GUI named
HW12_result_bhanford
In my second GUI I have this written in the opening function:
age = varargin{1}
athlete = varargin{2}
male = varargin{3}
female = varargin{4}
I then use these four variables(age, athlete, male, female) later in the second GUI and I
assume them to be the equivalent value of the corresponding variable passed from the first
GUI.
When I run everything the error that comes back is Index exceeds matrix dimensions.
if anyone could help me, that would be awesome. If you cannot help without the entire code I understand.

You use varargin if your argument list is variable, and varargin has to be in your function definition.
function HW12_result_bhanford(varargin)
In this case function receive a cell array as an input, so you can get individual arguments with varargin{1} etc.
If you put your arguments together as a structure, you can pass this structure as an argument along.
function HW12_result_bhanford(handles)
But if the function definition has individual arguments, for example,
function HW12_result_bhanford(age, athlete, male, female)
you cannot use varargin, just process the arguments as is.
Read more on how to use VARARGIN.

Related

Error "Too many return arguments are specified. Specify only one."

I get this error "Too many return arguments are specified. Specify only one."
I understand what it means, but it does not make any sense. Since I have already two output blocks and scope in my simulink file.
What could be the reason for this error?
This my "error" code:
[tout,yout]=sim("TP_sub.slx")
There is no problem with your simulink model, the problem is how you call the sim function. If you look at the docs, you see that sim only returns one output:
simOut = sim(modelname)
In earlier versions of Matlab, it was possible to add the state and output as additional output arguments, but currently you can only output a simOut object.
This simOut object will contain some information, but by default it will not contain the simulation time and model outputs.
You can obtain this data by adding additional arguments to the sim call (complete list here). For example, using the 'vdp' model,
mdl = 'vdp';
load_system(mdl);
simOut = sim(mdl, 'SaveOutput','on','OutputSaveName','yout', 'SaveTime', 'on')
you will obtain
simOut =
Simulink.SimulationOutput:
tout: [64x1 double]
yout: [64x2 double]
SimulationMetadata: [1x1 Simulink.SimulationMetadata]
ErrorMessage: [0x0 char]
from which you can get the simulation time, output 1 and 2 by
t = simOut.tout;
y1 = simOut.yout(:,1);
y1 = simOut.yout(:,2);
Another option to get the data in your workspace is to add To Workspace blocks, like you are already doing.
I understand what it means, but it does not make any sense.
What could be the reason for this error?
Obviously you are not aware that a and b in the following example may be something completely different:
[x,y] = myFunction(someValue)
a = [x,y]
b = myFunction(someValue)
At least if the function myFunction is a "mex function" (and most Simulink-related functions are!), the function myFunction can be defined in a way that totally different values are returned depending on the number of return values given:
[x,y]=myFunction(someValue) may return two 10x20 matrices and b=myFunction(someValue) may return a single number (1x1 matrix).
You cannot just use [x,y]=someFunction(someValue) to "split" a single value returned by the function someFunction into two parts!
The sim function returns one single value.
Thanks for your Comments . But actually it si possible to get multiple outputs from sim function . You just shoulld change" Model Confugiration Settings > Data Import/Export pane and UNCHECK Single simulation"

How to find all MATLAB function blocks in a Simulink model

I would like to know how to find all MATLAB function blocks in a Simulink model.
In a model in which I know there are a lot of MATLAB function blocks, I tried the following command:
find_system(myModel,'LookUnderMasks','on','FollowLinks','on','BlockType','MATLAB Function')
However, this command returns an empty cell array. If I try something like this:
find_system(myModel,'LookUnderMasks','on','FollowLinks','on','BlockType','Gain')
, I'm getting many results. Is the "MATLAB Function" an actual BlockType or is there another term to use?
You can use the following code to find all MATLAB function blocks.
S = sfroot();
% Get block handles
B = find(sfroot, '-isa','Stateflow.EMChart');
This will search all open models and returns a list of objects of type Stateflow.EMChart. You can look at the Path property of these objects to reduce the list to the model you want.
You will need to define the search depth use the below:
h=find_system(myModel,'SearchDepth',N, 'regexp', 'on', 'FollowLinks','on','Findall','on','LookUnderMasks','all', 'BlockType','Gain');
Specify N, the higher the N the deeper into the blocks the search will be.
Let me know if this doesn't work.

Matlab Function - ask for user input for given argument

I have a Matlab function that has numerous name-value parameter inputs. For some of the parameter names, there are a lot of possible values (which are not always obvious) that the user can choose from. What I would like to do is, IF the user calls the name, but does NOT give a value, THEN Matlab would display possible entries AND THEN take the user's input.
For example I have a function such as:
function getSomeData( varargin )
p=inputParser;
defaultData='abc';
addParameter(p, 'Data', defaultData);
parse(p,varargin{:});
end
If the user were to call the function in the command window such as:
>> getSomeData('Data')
in which the user did not give a value for 'Data', the window would display and prompt
>> getSomeData('Data')
No value for 'Data' Given
Possible Values of 'Data' are:
'abc'
'def'
'other'
Please input your 'Data':
in which I could use the result=input(prompt) function.
Any help or advice is very much appreciated! Cheers
May I ask you to specify the complexity of your input stuff. Either you come from java and think that you need to create an I/O object to be able to read inputs, or else your problem is more complex that the description gives the impression of.
Otherwise, I would give you the design of a less complicated way forward here. One way to do this is to use the nargin property, which finds the number of inputs to the function. Together with nargin, use an if statement (or switch-case?).
if nargin==0
% print alternative inputs with disp or fprintf.
% This alternative can also be replaced with comments (single block with
% no empty rows) right below the function. This will then be seen with
% the `help funName` command
elseif nargin==1
% Print description + permitted values. This can be done from a
% switch-case statement (if you want the switch-case statement
% can be placed in an external function).
elseif ~mod(nargin,2)
%parse input pairs and do the calculations.
else
error('wrong number of input arguments');
% or
% fprintf('wrong number of input arguments\n');
% set outputs to '', {}, [], ...
% return;
end
I hope this helps even though it is not exactly the solution proposed by you. This is however a simple solution with the advantage that you do not mix up the information parts and execution parts. My guess is that this is a convenient way to work with I/O without implementing a complicated parser.
These problems are otherwise normally solved by a complicated parser with a lot of different commands (compare with the terminal (unix based) of cmd prompt (windows)).

MATLAB cell array of function handles - How does it work?

I am trying to understand the following commands of a MATLAB script :
global operatorObj
calcEVR_handles = operatorObj.calcEVR_handles;
m = operatorObj.nInputs
E = zeros(m,1);
V = zeros(m,1);
R = zeros(m,m);
for i=1:m
[E(i), V(i), R(i,i)] = calcEVR_handles{i}(t,x);
end
What can calcEVR_handles be, if t is a float and x is a vector?
calcEVR_handles (to me) looks like a cell array where each element is a handle to a function. Each element in calcEVR_handles is an anonymous function that takes in a single value t and a single vector x. As such, by doing calcEVR_handles{i}, you would access the corresponding function stored at the ith element in the cell array. Once you have access, you then pass your parameters to this function and it gives you those three outputs.
To show you an example of this working, consider the following cell array that works similarly to calcEVR_handles.
calcCellFunc = {#sin, #cos, #tan};
This is a three element cell array, where each element is a handle to a function. The # is a special character in MATLAB that denotes that you are creating a handle to a function. It's also used to create anonymous functions, but let's shelve that for this answer. You can read more about it here if you want to delve into more detail regarding this.
Back to our cell array of handles, we will make handles for sin, cos and tan. You can then iterate over your cell array by accessing the function you want by calcCellFunc{idx} where idx is the element you want in the cell array. This will ultimately give you the function stored at index idx. Once you do that, you can then call the function and specify whatever inputs you want (or none if it doesn't take any inputs). Here's a quick example for you. Let's create a random 5 x 5 matrix, and run through each function with this matrix serving as the input. We then take each of these outputs and store them into a corresponding slot in an output cell array. As such:
rng(123); %// Set seed for reproducibility
M = rand(5);
calcCellFunc = {#sin, #cos, #tan};
out = cell(1, numel(calcCellFunc)); %// To store the results for each function
for idx = 1 : numel(calcCellFunc)
out{idx} = calcCellFunc{idx}(M); %// Get the function, then pass
%// the matrix M to it
end
If you want to make things clear, you could split up the out statement to this instead:
func = calcCellFunc{idx}; %// Get access to the function
out{idx} = func(M); %// Pass M to this function
If you're new to handles / anonymous functions, you should probably use the above code first to make it explicitly clear on what MATLAB is doing. You are first getting access to the function you want that is stored in the cell array, and then you pass your arguments to this function.
If we display the output, we get:
>> celldisp(out)
out{1} =
0.6415 0.4106 0.3365 0.6728 0.5927
0.2823 0.8309 0.6662 0.1815 0.7509
0.2249 0.6325 0.4246 0.1746 0.6627
0.5238 0.4626 0.0596 0.5069 0.5737
0.6590 0.3821 0.3876 0.5071 0.6612
out{2} =
0.7671 0.9118 0.9417 0.7398 0.8054
0.9593 0.5564 0.7458 0.9834 0.6604
0.9744 0.7745 0.9054 0.9846 0.7489
0.8518 0.8866 0.9982 0.8620 0.8191
0.7522 0.9241 0.9218 0.8619 0.7502
out{3} =
0.8363 0.4503 0.3573 0.9094 0.7359
0.2942 1.4934 0.8932 0.1845 1.1370
0.2308 0.8167 0.4690 0.1773 0.8850
0.6149 0.5218 0.0597 0.5880 0.7004
0.8761 0.4135 0.4205 0.5884 0.8814
The first element of the output cell array has the output when you pass M to sin, the second when you pass M to cos, and the third when you pass M to tan.
So the next question you're asking... why is this useful?
Point #1 - Nix the copying and pasting
This kind of code writing is very useful because if you want to use the same inputs and supply them to many different functions, we would naturally be inclined to do some copying and pasting. Take each of your function names, and create a single line for each. Each line would call the corresponding function you want, followed by the input arguments. This can become quite tedious, and so one smart way to do it would be to place your function name as a handle into a cell array, and to write one for loop that goes over all of the functions dynamically. You could even explore cellfun and escape using the for loop to iterate over all of the function handles too, but I'll leave that for you to read up on.
In this way, you have very maintainable code and if you want to remove functions that don't need to be run, just remove the handles from the cell array rather than scrolling down to where the line that invokes this function is located and removing that.
This is actually a very common technique in computer science / software engineering in general. In fact, this is actually quite close to what are known as function pointers. This is MATLAB's cheap way of doing it, but the logic behind this is essentially the same.
Point #2 - Higher Order Functions
Another way this is useful is if you have a function where one (or more than one!) of the inputs is a function, and you also specify inputs into this function as additional parameters to this function. This is what is known as a higher order function. The outputs would be based on using this input function, and the additional inputs you specify to it and the outputs are based on using this input function and the inputs you specify for this function.
One very good example is the fzero function in MATLAB. The goal is to find the root of a non-linear function, and the first parameter is a handle to a function that you specify. The base behaviour behind how fzero works is the same no matter what the function is. All you have to do is specify the function you want to solve and the initial guess of where you think this root is.
All in all, anonymous functions are very useful.

How to get all outputs (MatLab)?

Suppose I have a function that gives out unknown number of output arguments (it depends on input,thus change through the loops). How to get all of them?
nargout doesn't help as the function uses varargout (the result is -1)
And of course I can't rewrite the function, otherwise the question wouldn't arise :- )
Well, thanks to all partisipated in discussion. Summing up, it seems the problem has no general solution, because MatLab itself estimates the number of desired outputs before the function call to use inside it. Three cases can be pointed out though:
1) The funcrion doesn't have varargout in definition, thus nOut=nargout(#fcn) returns positive number.
Then nOut is an actual number of outputs and we can use a cell array and a column list trick.
X=cell(1,nOut);
[X{:}]=fcn(inputs);
2) The funcrion has varargout in definition, thus nOut=nargout(#fcn) returns negative number. However some correlation with inputs can be found (like length(varargin)=length(varargout)).
Then we can calculate the resulting nOut from inputs and perform the above column list trick.
3) You know the fcn developer.
Ask him fot assistance. For example to make the function's output to be a cell array.
One of ways I usually use in this case is to store all outputs in a cell array inside the function. Getting the cell array outside the function's body, you might investigate its length and other properties.
Here is how you could deal with the problem in general. I didn't mention this solution earlier because... it is horrible.
Suppose a function can have 1 or 2 output arguments:
try
[a, b] = f(x)
catch
a = f(x)
end
Of course it is possible to do this for any number of output arguments, but you really don't want to.