Adding loop values to an array
3 次查看(过去 30 天)
显示 更早的评论
Hello,
I'm trying to perfom a simulation that will calculate a value for a given input and then store than input in an array such that I can graph it. However, i can't seem to be able to store the values in an array. I'm brand new to MATLAB.
Any help would be greatly appreciated.
PS, I have tried to comment the code and make what I want to happen as clear as possible.
PPS, please note, should result in a real and imaginery part.
ctc, clear
%declaring variables
rho = 1.22;
c0 = 344;
fillRat = 0.098;
dampRat = 0.03;
Fr = 417;
K = rho*(c0)^2;
Kr = rho*(c0)^2;
%%calcaulating Keff
%define mamFrequency range:
mamFrequency = 200 : 600;
%Loop through each value of mamFrequency
for j = mamFrequency
omegR = j/Fr; %dependancy--
Keff = K/((1 - fillRat) + (K/Kr)*(fillRat/(1 + 2i * dampRat * omegR - (omegR)^2)));%analytical equation
%calculating Keff/K
modulRat = Keff/K; %want to store modulRat value for each iteration of so can plot later
end
%plotting modulRat (y-axis) against i - the mamFrequency value (x-axis)
figure(1)
plot(j,modulRat);
0 个评论
采纳的回答
Richard Fiifi Annan
2021-4-1
This is an improved version of VBBV's answer. Just like he mentioned, it plots only the real part by default. Make your choice!
CHOICE 1:
% iteration for each value of mamFrequency:
modulRat = zeros(length(mamFrequency), 1); % memory pre-allocation
for j = 1:length(mamFrequency)
omegR = (mamFrequency(j)/Fr);
Keff = K/((1 - fillRat) + (K/Kr)*(fillRat/(1 + 2i * dampRat * omegR - (omegR)^2)));%analytical equation
modulRat(j,1) = Keff/K;
end
% plotting the result:
figure
plot(mamFrequency, modulRat)
CHOICE 2:
% iteration for each value of mamFrequency:
modulRat = cell(length(mamFrequency), 1); % memory pre-allocation
for j = 1:length(mamFrequency)
omegR = (mamFrequency(j)/Fr);
Keff = K/((1 - fillRat) + (K/Kr)*(fillRat/(1 + 2i * dampRat * omegR - (omegR)^2)));
modulRat{j,1} = Keff/K;
end
modulRat = cell2mat(modulRat); % convert cell to matrix
% plotting the result
figure
plot(mamFrequency, modulRat)
2 个评论
Richard Fiifi Annan
2021-4-1
Memory pre-allocation speeds up the computation. You will appreciate it if you have a very large matrix or vector.
更多回答(1 个)
Richard Fiifi Annan
2021-4-1
real_part = real(modulRat );
imaginary_part = imag(modulRat );
figure
plot(mamFrequency, real_part, 'r', mamFrequency, imaginary_part,'b')
legend({'real part', 'imaginary part'})
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!