Adding loop values to an array

2 ビュー (過去 30 日間)
Joshua Tshuma
Joshua Tshuma 2021 年 4 月 1 日
回答済み: Richard Fiifi Annan 2021 年 4 月 1 日
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);

採用された回答

Richard Fiifi Annan
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
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.
Joshua Tshuma
Joshua Tshuma 2021 年 4 月 1 日
Awesome! Thank you both! The code is working well, with an expected output for the real part. Would you know how I can compute the imaginary part?

サインインしてコメントする。

その他の回答 (1 件)

Richard Fiifi Annan
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'})

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by