Obtaining values from a loop

조회 수: 1 (최근 30일)
mads skibsted
mads skibsted 2024년 3월 7일
댓글: Dyuman Joshi 2024년 3월 11일
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?
Dyuman Joshi
Dyuman Joshi 2024년 3월 11일

댓글을 달려면 로그인하십시오.

채택된 답변

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