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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With