For loop inside for loop

Hi, I have the following function that I am using with a single rho(1x654545) -attached. The result gives me the single peaks(1x1023). I would like to modify the script so that I can use as input rho(4x654545) and end up with the result peaks(4x1023).
Can I get some help? Thanks
x = diff(sign(rho));
indx = find(x>0);
for jj=2:length(indx);
tmp = rho(indx(jj-1):(indx(jj)));
test = dt*(indx(jj)-indx(jj-1));
peaks(jj) = max(tmp);
end

4 comentarios

KL
KL el 15 de Ag. de 2017
Yes, read this .
Adam
Adam el 15 de Ag. de 2017
There doesn't seem to be any guarantee that you will have 1023 values > 0 for each of your 4 rho arrays.
Isma_gp
Isma_gp el 15 de Ag. de 2017
Yes, that is true. The number of values >0 could vary.
Adam
Adam el 15 de Ag. de 2017
In that case you'd have to use a cell array or a 2d numeric array with enough rows for the case with most peaks and leave NaNs in the extra rows for the other columns.

Iniciar sesión para comentar.

Respuestas (1)

Arjun
Arjun el 5 de Dic. de 2024

0 votos

I see that currently you are processing a row vector to extract a row vector containing peaks and want to extend this functionality for a matrix.
Since each row of the matrix can have different number of peaks and hence returning a matrix of peaks will not be suitable. You can return a cell array instead which will contain same number of rows as in the input matrix and a single column containing a vector of peaks.
Kindly refer to the code below for better understanding:
num_rows = size(rho, 1);
% Initialize a cell array
peaks = cell(num_rows, 1);
for i = 1:num_rows
x = diff(sign(rho(i, :)));
indx = find(x > 0);
% Temporary array to collect peaks for the current row
row_peaks = [];
for jj = 2:length(indx)
tmp = rho(i, indx(jj-1):indx(jj));
% Append the peak to the temporary array
row_peaks(end+1) = max(tmp);
end
% Store the peaks for the current row in the cell array
peaks{i} = row_peaks;
end
Kindly refer to the attached documentation link understand more about the “cell array”: https://www.mathworks.com/help/releases/R2021a/matlab/ref/cell.html
I hope this will help!

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 15 de Ag. de 2017

Respondida:

el 5 de Dic. de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by