4

How do i implement elitism in matlab? For example, i run a program and after each run, a value is save in a variable say a and after completing all the runs, say 6 runs i have the a as follows

a = [7, 5, 4, 3, 6, 8];

how can i apply elitism on a to end of having the content of a as a = [7, 5, 4, 3, 3, 3];

That is when i scan through a, i will replace the bigger number with the small one i encounter. From the example, after scanning through a, 5<7, so i keep 5, 4<5, so i keep 4, 3<4, so i keep 3, 3<6, so i replace 6 with 3, and again 3< 8, so i replace 8 with 3 to end of having the a as a = [7, 5, 4, 3, 3, 3];

how do u do this in Matlab.

Attempt

I said,

if a(i)< a(i+1)
a(i+1) = a(i);
end

plot(a); 

so that i can have a graph that decents smoothly.

but i keep having the following error:

'Subscript indices must either be real positive integers or logicals.'

Any idea how i can do this correctly.

Cape Code
  • 3,584
  • 3
  • 24
  • 45
David Wang
  • 43
  • 3
  • Also see [this question](http://stackoverflow.com/questions/20054047/subscript-indices-must-either-be-real-positive-integers-or-logicals-generic-sol) for a [generic approach](http://stackoverflow.com/a/20054048/983722) to deal with this error. – Dennis Jaheruddin Mar 10 '14 at 10:40

3 Answers3

4

I believe this should work for all cases:

b = [a(1), arrayfun(@(n) min(a(1:n)), 2:length(a))]

a =
     7     4     3     6     5     2     5
b =
     7     4     3     3     3     2     2

For info:

Your initial thought was correct, but you forgot to put the if inside a loop. You could have done:

for ii = 1:length(a)-1
   if a(ii)< a(ii+1)
      a(ii+1) = a(ii);
   end
end

The reason why you got the error was because you probably hadn't defined i, thus MATLAB interpreted it as the imaginary unit (sqrt(-1)). That's also the reason why I used ii instead of i in the loop, to avoid such errors.

Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
  • Thanks. You are right. My initial thoughts were right. I just put the if statement in a loop as you suggested and it worked. – David Wang Jan 22 '14 at 22:42
2

Edited to work with local minima:

a = [7, 5, 4, 3, 6, 8];
[y, i] = findpeaks(-a, 'npeaks', 1) ;
a(i:end)=-y;
plot(a)

The plot:

a plotted

Cape Code
  • 3,584
  • 3
  • 24
  • 45
2

An alternative to Robert P.'s answer without arrayfun:

min(triu(repmat(a(:),1,numel(a))) + tril(NaN(numel(a)),-1))
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147