I think this does what you want, without loops:
d = diff(x);
ind = [false d<0] & [d>0 false];
a = find(ind);
b = x(ind);
Pergunta
I want to define a function in matlab that gives a vector as input and gives local minimals as output in the form of a matrix. but i give this error:Too many output arguments. here is my code
function [index, value] = localminima(x)
N = length(x);
a = [];
b = [];
% at first a & b witch are index and value, respectively are empty
% then, in the for loop indexes and values of local minimal are added
% to a & b.
for k = 2:N-1,
if((x(k) < x(k+1)) && (x(k) < x(k-1)))
a = [a; k];
b = [b; x(k)];
end
end
[index, value] = [a, b]
Solução
I think this does what you want, without loops:
d = diff(x);
ind = [false d<0] & [d>0 false];
a = find(ind);
b = x(ind);
Outras dicas
When you're trying to assign the values a
and b
to index
and value
MATLAB is actually concatenating them into a single vector which it can't assign to two output variables. Instead you could use index = a; value = b
or just replace the variable names a
and b
alltogether with index
and value
.
Furthermore, performance will probably improve if you don't use a loop but instead use MATLABs built-in functions and logical indexing, so e.g.
function [index, value] = localminima(x)
dx = diff(x);
logicalIndex = [ false dx < 0 ] & [ dx > 0 false ];
index = find(logicalIndex);
value = x(logicalIndex);
end
[index, value] = [a, b]
is incorrect. You should have two separate assignments:
index = a;
value = b;
To get both index
and value
vectors as outputs from your function, you should call the function in MATLAB command windows as
>> [index, value] = localminima(x)
A bit of an explanation: Both sides of [index, value] = [a, b]
look similar, but they mean different things.
[a, b]
is constructing an nx2
matrix by concatenating the nx1
vectors a
and b
.[index, value]
is trying to assign the result from the right-hand side of the =
symbol to two variables: index
and value
. Since [a,b]
is a single variable, which is a matrix, [index, value] = [a, b]
is an invalid operation: there is nothing to assign to the variable value
.[index, value] = localminima(x)
and define index=...
and value= ...
in your function as two separate variables, then your function will return two outputs. Hence [index, value] = localminima(x)
will be a valid operation.