Obtaining values from a loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
mads skibsted
am 7 Mär. 2024
Kommentiert: Dyuman Joshi
am 11 Mär. 2024
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 Kommentare
Dyuman Joshi
am 11 Mär. 2024
Pre-allocate a cell array and store the values in each iteration - Preallocate arrays, https://in.mathworks.com/help/matlab/matlab_prog/preallocate-memory-for-a-cell-array.html
Akzeptierte Antwort
Rohit Kulkarni
am 11 Mär. 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!
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!