Adding loop values to an array

조회 수: 3 (최근 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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by