Borrar filtros
Borrar filtros

Applying function on few elements each time, using a for loop

2 visualizaciones (últimos 30 días)
Zuha Yousuf
Zuha Yousuf el 13 de Abr. de 2020
Editada: Rik el 13 de Abr. de 2020
So lets say I have an array, which has 540000 values. I want to apply a max function over this array, but only over 30000 values each time, using a for loop. Is there a way I could do this??

Respuestas (2)

Ameer Hamza
Ameer Hamza el 13 de Abr. de 2020
Editada: Ameer Hamza el 13 de Abr. de 2020
You can do it without for loop in MATLAB
x = rand(1,540000); % random data replace it with your vector
y = max(reshape(x, 30000, []));
  2 comentarios
Zuha Yousuf
Zuha Yousuf el 13 de Abr. de 2020
Hey, thanks for answering! So what I meant was, that I need to apply this function one at a time over this chosen sample window each time.
The code you gave me gives me an error that 'Array indices must be positive integers or logical values'.
Ameer Hamza
Ameer Hamza el 13 de Abr. de 2020
Yes, This code applies the max function using a window of 30000 numbers. Then move the window to the next block and apply max. Can you make sure there is no variable named 'max' in your workspace? Otherwise, paste your code here, which gives this error.

Iniciar sesión para comentar.


Rik
Rik el 13 de Abr. de 2020
Editada: Rik el 13 de Abr. de 2020
If you don't mean what Ameer posted, then you could mean a sliding window maximum. You could write it yourself with a loop, but it is more efficient to use the builting movmax function.
If you are using an older release (or insist on a loop) you can use something like this:
x = rand(1,540000); % random data
window_size=30000;
output=zeros(size(x));
window=ceil(window_size*[-0.5 0.5]);
for n=1:numel(x)
start=max(1,n+window(1));%ensure positive starting index with max(1,__)
stop=min(n+window(2),numel(x));%ensure value stays within bounds
output=max(x(start:stop));
end
%test:
isequal(output,movmax(x,abs(window))) %returns true

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by