MATLAB: For-loop refuses to save five values in 1 vector, instead saves one value in 5 vector. How to fix this

forlooploop

function [mextreme]=myextreme(Mloc,npl)
mextreme=[];
for p=2:npl-1
if abs(Mloc(p))>abs(Mloc(p+1))&& abs(Mloc(p))>abs(Mloc(p-1))
mextreme=[mextreme Mloc(p)];
end
end
The result is get is:
mextreme =
0.0723
mextreme =
0.0592
mextreme =
[]
mextreme =
0.0772
mextreme =
[]
I want something looking like this:
mextreme=[0.0723 0.0592 0 0.0772 0]
How do I accomplish this?

Best Answer

Use vector solution...one of many ways
x=abs(x);
mextreme=x([false and(diff(x(1:end-1))>0,diff(x(2:end))<0)]);
Example (at command line)--
>> x=rand(1,10)
x =
0.5853 0.5497 0.9172 0.2858 0.7572 0.7537 0.3804 0.5678 0.0759 0.0540
>> and(diff(x(1:end-1))>0,diff(x(2:end))<0)
ans =
0 1 0 1 0 0 1 0
>> find(ans)+1
ans =
3 5 8
>> x(ans)
ans =
0.9172 0.7572 0.5678
>>
ADDENDUM
With the additional detail of the underlying problem, the overall solution required a couple of rearrangements -- first to accumulate the total length of the moment vector concatenated together "Mbeam" and then remove the call to compute the limits from that routine to be called from the top level function after building the beam--
function [Mbeam, mextreme, idx]=projekt % note return values added
...as is to here...
Mbeam=moment(npl,MA,RA,q,nfack,L); % moment rewritten to not call myextreme
[mextreme,idx]=myextreme(Mbeam) % computes extrema and locations
end
The revised functions are...
function Mbeam=moment(npl,MA,RA,q,nfack,L)
Mbeam=[];
for i=1:nfack
x=linspace(0,L(i),npl);
Mloc=MA(i)+RA(i)*x+(q(i)*x.^2)/(2);
Mbeam=[Mbeam Mloc];
end
end
function [mextreme,ix]=myextreme(Mloc)
x=abs(Mloc);
ix=find([false and(diff(x(1:end-1))>0,diff(x(2:end))<0)]);
mextreme=Mloc(ix);
end
NB: Two fixups in myextreme
  1. To get the locations, revert to find for indexing, and
  2. Use the input vector to return the sign of the extrema as well as magnitude
and a last in the main routine
  1. Return the desired values to the caller so don't go away on completion
I believe this accomplishes your task...your were pretty close excepting not seeing to use the whole vector after it was built instead of during each segment.
With the above changes you will have Mbeam and the two associated variables mextreme,idx for the extreme points. Note also that since you used a function, in order to have these values after the function completes you've got to return them to the caller or workspace or they go out of context when projekt completes which doesn't do a lot of good... :)