How to get the highest value from the latest samples?

I have code that calculates an error for each sample, and I would like to always get the highest value from the last samples.
error(n,1)=Ia(n)-Ia_future(n,1)
p(n,1) = (1+0.2)*max(error(n-1,1))
I want to get the maximum value of the last n samples of error(n-1,1) that were calculated. The "max" above there is just to demonstrate what I'm trying to say.

2 Commenti

You mean like max(error((end+1-n):end,1))?
Other than that, you should really not use error as a variable name.
Yes, exactly that!

Accedi per commentare.

 Risposta accettata

error is a built-in function so don't call your variable that. Call it errors or differences instead.
Is this what you mean:
Ia_future = rand(5, 3) % Create sample data.
Ia = rand(5, 1)
% Initialize/preallocate p.
p = zeros(size(Ia));
[rows, columns] = size(Ia_future)
for n = 1 : rows % For every row...
% We're now on iteration "n".
% Subtract the "last" n values,
% meaning the values we've seen "so far"
% which would be the values from 1 to n.
errorsSoFar = Ia(1:n) - Ia_future(1:n,1)
% Put into an equation to get p.
p(n) = (1+0.2)*max(errorsSoFar)
end

5 Commenti

I had already done the part with the for, I was having problems with the dimension, because the n-1 passed value didn't exist, it was like this:
for n = 1:size(t,1)
if n>=4
X = [Ia(n-1,1) Ia(n-2,1) ; Ia(n-2,1) Ia(n-3,1)];
future = [Ia(n,1) ; Ia(n-1,1)];
C = ((X.')*(X))'*(X.')*(future);
Ia_future(n,1) = C(1,1)*Ia(n,1)+C(2,1)*Ia(n-1,1);
PE(n,1)=Ia(n)-Ia_future(n,1);
p(n,1) = (1+0.2)*max(PE((end+1-n):end,1)) % the part of Rik comment
end
end
If you have an vector that you're indexing over in a loop, what do you consider the "last" values to be?
  1. The values you've seen (indexed) already, so Ia(1:n), or (like "last" means last seen or "prior")
  2. The rightmost values in the vector : Ia(end-n+1 : end) (the end of the array regardless of what the loop index is currently at)
In the case I look for, the highest value among the samples already calculated. It doesn't have to be the largest value of the entire vector.
So that would be case 1, and I gave code for that. But you didn't seem to try it. Why not?
I just tested it, it worked.
I was thinking that I should disregard the n-1 value of the first sample but it wasn't necessary. Thanks!

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by