Obtaining values from a loop

1 view (last 30 days)
How can I store all the data in a matrix from this loop?
for i = 1:size(q,2)
[Maxima(:),MaxIdx(:)] = findpeaks(q(:,i));
[Minima,MinIdx] = findpeaks(-q(:,i));
end
figure; hold on
plot(t(MaxIdx),Maxima,'o');
plot(t(MinIdx),-Minima,'o');
plot(t,q)
  4 Comments
mads skibsted
mads skibsted on 7 Mar 2024
Thanks a lot!
Another problem is that i wanted to store all the minima and maxima in one large matrix for all the sine curves at the end of the loop.
Can you maybe help me with that?

Sign in to comment.

Accepted Answer

Rohit Kulkarni
Rohit Kulkarni on 11 Mar 2024
Hi Mads,
In my understanding you want to obtain all the information from a matrix using loops.
Here is an example that shows the use of code provided by you on a sample matrix "q" and sample time vector "t":
% Sample time vector
t = linspace(0, 10, 1000); % 0 to 10 seconds, 1000 points
% Sample matrix q with sinusoidal columns of different frequencies
q = [sin(2 * pi * 1 * t); sin(2 * pi * 1.5 * t); sin(2 * pi * 2 * t)]';
% Note: q is transposed to match the expected dimensions (rows are time points)
% Initialize cell arrays to store maxima and minima information
Maxima = cell(1, size(q, 2));
MaxIdx = cell(1, size(q, 2));
Minima = cell(1, size(q, 2));
MinIdx = cell(1, size(q, 2));
% Loop through each column of q
for i = 1:size(q, 2)
[maxima, maxIdx] = findpeaks(q(:,i));
[minima, minIdx] = findpeaks(-q(:,i)); % To find minima
% Store in cell arrays
Maxima{i} = maxima;
MaxIdx{i} = maxIdx;
Minima{i} = -minima; % Convert back to positive values
MinIdx{i} = minIdx;
end
% Plotting
figure; hold on
% Iterate over each column's results to plot
for i = 1:size(q, 2)
plot(t(MaxIdx{i}), Maxima{i}, 'o', 'MarkerEdgeColor', 'r');
plot(t(MinIdx{i}), Minima{i}, 'o', 'MarkerEdgeColor', 'b');
end
plot(t, q) % Plot the original sinusoidal waves
xlabel('Time (s)');
ylabel('Amplitude');
title('Maxima and Minima of Sinusoidal Waves');
legend({'Maxima', 'Minima', 'Waveforms'}, 'Location', 'best');
grid on;
Refer to the following documentation to know more about cell arrays:
Hope this resolves your query!

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!