Obtaining values from a loop

1 次查看(过去 30 天)
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 个评论
mads skibsted
mads skibsted 2024-3-7
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?

请先登录,再进行评论。

采纳的回答

Rohit Kulkarni
Rohit Kulkarni 2024-3-11
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!

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by