Weird array assignment in MATLAB: [x,t]=house_dataset - arrays

I'm learning work with neural networks through MATLAB samples. In one sample of the documentation (R2012a), there is a weird assignment
[x,t] = house_dataset
Basically, house_dataset is a 13×506 2D array. But the assignment results in two arrays:
x, a 13×506 2D array which is to be used as input to our neural network; t a 1×506 array which is to be used as target for network.
I don't know how this is done. Is it based on some fundamental thing I don't know about MATLAB matrices?
I even assigned house_dataset into another variable
h_dataset = house_dataset;
and then MATLAB gave an error when I tried to do this:
[x,t] = h_dataset;
Error message reads:
>> [x,t] = h_dataset;
Too many output arguments.
Does anyone know what this is all about?

It is normal behaviour for functions (and house_dataset is one of many functions in toolbox)
Function returns 2 values
function [inputs,targets] = house_dataset
but if you just enter
variable = house_dataset;
it returns and saves to variable only first value which is [inputs]
check the behaviour of very simple function
function [out1,out2] = test
out1 = 'first out';
out2 = 'second out';
end
and then call in matlab command window:
[first, second] = test
first = test
second = test
if you want to get only second value use something like:
[~,second] = test

Related

generalizing scalar inputs to array inputs for user-defined fucntions

The round function can take a scalar and operate on it. However it can also take an array and operate on it in expected manner.
>> round(2.3)
ans =
2
>> round([2.3,3.4])
ans =
2 3
I similarly have a function and want it to work in the ""expected"" manner for array inputs. It works well for scalar inputs. I could run a for loop and evaluate my function on each element of the array but what other smarter ways do i have available?
For further concreteness, i have:
function [a,b]=func(c,d,e,f)
And i have d,e,f but i want to evaluate the function to several values of c:-
g=[];
for i=1:10
[a,b]=func(c(i),d,e,f);
g=[g;[a,b]];
end
I am not fully sure how to apply arrayfun though i believe it is what i should use.
What you are looking for is the arrayfun function.
Here is the documentation: http://www.mathworks.com/help/matlab/ref/arrayfun.html
Say, I have this function:
function res = myTest(a,b)
size(a) % for checking that we work on each element
res = a+1;
res = res +b;
I have a matrix A
A = magic(3);
I want to apply myTest with a equal to each element in A
A1 = arrayfun(#(x) myTest(x,2),A)
(x is replaced by the elements of the array declared after the comma)

What is the point of cell indexing in MATLAB

The point of indexing is mainly to get the value. In MATLAB,
for a cell array, there is content indexing ({}), and thus cell indexing (()) is only for selecting a subset from the cell array, right?
Is there anything other advanced usage for it? Like using it as
a pointer and pass it to a function?
There is a heavily simplified answer. {}-indexing returns you the content, ()-indexing creates a subcell with the indexed elements. Let's take a simple example:
>> a=x(2)
a =
[2]
>> class(a)
ans =
cell
>> b=x{2}
b =
2
>> class(b)
ans =
double
Now continue with non-scalar elements. For the ()-indexing everything behaves as expected, you receive a subcell with the elements:
>> a=x(2:3)
a =
[2] [3]
The thing really special to Matlab is using {}-indexing with non-scalar indices. It returns a Comma-Separated List with all the contents. Now what is happening here:
>> b=x{2:3}
b =
2
The Comma-Separated List behaves similar to a function with two return arguments. You want only one value, only one value is assigned. The second value is lost. You can also use this to assign multiple elements to individual lists at once:
>> [a,b]=x{2:3} %old MATLAB versions require deal here
a =
2
b =
3
Now finally to a very powerful use case of comma separated lists. Assume you have some stupid function foo which requires many input arguments. In your code you could write something like:
foo(a,b,c,d,e,f)
Or, assuming you have all parameters stored in a cell:
foo(a{1},a{2},a{3},a{4},a{5},a{6})
Alternatively you can call the function using a comma separated list. Assuming a has 6 elements, this line is fully equivalent to the previous:
foo(a{:}) %The : is a short cut for 1:end, index the first to the last element
The same technique demonstrated here for input arguments can also be used for output arguments.
Regarding your final question about pointers. Matlab does not use pointers and it has no supplement for it (except handle in oop Matlab), but Matlab is very strong in optimizing the memory usage. Especially using Copy-on-write makes it unnecessary to have pointers in most cases. You typically end up with functions like
M=myMatrixOperation(M,parameter,parameter2)
Where you input your data and return it.

Arrays containing text in MATLAB

In MATLAB, when code like this is implemented:
c = ['a','b','c','d'];
you can't really do anything with the elements. To illustrate my example:
>> c
c =
abcd
and when you do c(1,1) it returns A. But for c(2,1) it returns Index exceeds matrix dimensions.
To combat this problem, is there any way I could get around it? Or perhaps a different type of array?
You need to store each string in a different row, like so:
c = ['a';'b';'c';'d'];
What you have done above is use the [], which is the string concatenation operator. What it outputs is a single string, 'abcd', stored in c(1), which is why c(2) throws an index error.
Alternatively, you could use cell arrays :
c{1} = 'a';
c{2} = 'b';

indexed object dot notation method gives scalar property

I'm seeing an issue when I try and reference an object property after having used a dot notation to apply a method.
it only occurs when I try to index the initial object
classdef myclassexample
properties
data
end
methods
function obj = procData(obj)
if numel(obj)>1
for i = 1:numel(obj)
obj(i) = obj(i).procData;
end
return
end
%do some processing
obj.data = abs(obj.data);
end
end
end
then assigning the following
A = myclassexample;
A(1).data= - -1;
A(2).data = -2;
when calling the whole array and collecting the property data it works fine
[A.procData.data]
if i try and index A then i only get a scalar out
[A([1 2]).procData.data]
even though it seems to do fine without the property call
B = A([1 2]).procData;
[B.data]
any ideas?
I would definitely call this a bug in the parser; A bug because it did not throw an error to begin with, and instead allowed you to write: obj.method.prop in the first place!
The fact that MATLAB crashed in some variations of this syntax is a serious bug, and should definitely be reported to MathWorks.
Now the general rule in MATLAB is that you should not "index into a result" directly. Instead, you should first save the result into a variable, and then index into that variable.
This fact is clear if you use the form func(obj) rather than obj.func() to invoke member methods for objects (dot-notation vs. function notation):
>> A = MyClass;
>> A.procData.data % or A.procData().data
ans =
[]
>> procData(A).data
Undefined variable "procData" or class "procData".
Instead, as you noted, you should use:
>> B = procData(A): % or: B = A.pocData;
>> [B.data]
FWIW, this is also what happens when working with plain structures and regular functions (as opposed to OOP objects and member functions), as you cannot index into the result of a function call anyway. Example:
% a function that works on structure scalar/arrays
function s = procStruct(s)
if numel(s) > 1
for i=1:numel(s)
s(i) = procStruct(s(i));
end
else
s.data = abs(s.data);
end
end
Then all the following calls will throw errors (as they should):
% 1x2 struct array
>> s = struct('data',{1 -2});
>> procStruct(s).data
Undefined variable "procStruct" or class "procStruct".
>> procStruct(s([1 2])).data
Undefined variable "procStruct" or class "procStruct".
>> feval('procStruct',s).data
Undefined variable "feval" or class "feval".
>> f=#procStruct; f(s([1 2])).data
Improper index matrix reference.
You might be asking yourself why they decided to not allow such syntax. Well it turns out there is a good reason why MATLAB does not allow indexing into a function call (without having to introduce a temporary variable that is), be it dot-indexing or subscript-indexing.
Take the following function for example:
function x = f(n)
if nargin == 0, n=3; end
x = magic(n);
end
If we allowed indexing into a function call, then there would be an ambiguity in how to interpret the following call f(4):
should it be interpreted as: f()(4) (that is call function with no arguments, then index into the resulting matrix using linear indexing to get the 4th element)
or should it interpreted as: f(4) (call the function with one argument being n=4, and return the matrix magic(4))
This confusion is caused by several things in the MATLAB syntax:
it allows calling function with no arguments simply by their name, without requiring the parentheses. If there is a function f.m, you can call it as either f or f(). This makes parsing M-code harder, because it is not clear whether tokens are variables or functions.
parentheses are used for both matrix indexing as well as function calls. So if a token x represents a variable, we use the syntax x(1,2) as indexing into the matrix. At the same time if x is the name of a function, then x(1,2) is used to call the function with two arguments.
Another point of confusion is comma-separated lists and functions that return multiple outputs. Example:
>> [mx,idx] = max(magic(3))
mx =
8 9 7
idx =
1 3 2
>> [mx,idx] = max(magic(3))(4) % now what?
Should we return the 4th element of each output variables from MAX, or 4th element from only the first output argument along with the full second output? What about when the function returns outputs of different sizes?
All of this still applies to the other types of indexing: f()(3)/f(3), f().x/f.x, f(){3}/f{3}.
Because of this, MathWorks decided avoid all the above confusion and simply not allow directly indexing into results. Unfortunately they limited the syntax in the process. Octave for example has no such restriction (you can write magic(4)(1,2)), but then again the new OOP system is still in the process of being developed, so I don't know how Octave deals with such cases.
For those interested, this reminds me of another similar bug with regards to packages and classes and directly indexing to get a property. The results were different whether you called it from the command prompt, from a script, or from a M-file function...

Making outputs from an array in Matlab?

I have an array of 20 items long and I would like to make them an output so I can input it into another program.
pos = [0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,]
I would like to use this as inputs for another program
function [lowest1, lowest2, highest1, highest2, pos(1), pos(2),... pos(20)]
I tried this and it does not work is there another way to do this?
I'm a little confused why you'd want to do that. Why would you want 20 outputs when you could just return pos as a single output containing 20 elements?
However, that said, you can use the specially named variable varargout as the last output variable, and assign a cell to it, and the elements of the cell will be expanded into outputs of the function. Here's an example:
function [lowest1, lowest2, highest1, highest2, varargout] = myfun
% First set lowest1, lowest2, highest1, highest2, and pos here, then:
varargout = num2cell(pos);
If what you're trying to do is re-arrange your array to pass it to another Matlab function, here it is.
As one variable:
s=unique(pos);
q=[s(1) s(2) s(end-1) s(end) pos];
otherFunction(q);
As 24 variables:
s=unique(pos); otherFunction(s(1), s(2), s(end-1), s(end), pos(1), pos(2), pos(3), pos(4), pos(5), pos(6), pos(7), pos(8), pos(9), pos(10), pos(11), pos(12), pos(13), pos(14), pos(15), pos(16), pos(17), pos(18), pos(19), pos(20));
I strongly recommend the first alternative.
Here are two examples of how to work with this single variable. You can still access all of its parts.
Example 1: Take the mean of all of its parts.
function otherFunction(varargin)
myVar=cell2mat(varargin);
mean(myVar)
end
Example 2: Separate the variable into its component parts. In our case creates 24 variables named 'var1' to 'var24' in your workspace.
function otherFunction(varargin)
for i=1:nargin,
assignin('base',['var' num2str(i)],varargin{i});
end
end
Hope this helps.
Consider using a structure in order to return that many values from a function. Carefully chosen field names make the "return value" self declarative.
function s = sab(a,b)
s.a = a;
s.b = b;

Resources