Using an array as an element in a function.
24 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hello,
I am having trouble getting an array and a function to co-operate. I am trying to setup array "V=[1:4]" and have the equations run for all values of %error. Without an array my at_volume is returning as 1 always. Below is my goal, code, and error.
code to call (that ive been using to test) IdealGasLaw(1, 300, [1:4])
% Define your function file here
function [p_Ideal, p_Waals] = IdealGasLaw(n, T, V);
R = 0.08206;
a = 1.39;
b = 0.0391;
V = [1:4]
p_Ideal = (n*R*T) / V;
p_Waals = ((n*R*T)/(V-n*b)) - ((n^2)*a)/V^2;
error = (p_Ideal - p_Waals) / p_Waals;
max_error = max(error)
[max_error, idx_of_max] = max(error)
0 Commenti
Risposte (1)
Stephen23
il 1 Ott 2022
Modificato: Stephen23
il 1 Ott 2022
Use element-wise division ./ not matrix division /
You will probably also need to use element-wise power .^, not matrix power ^
Learning the difference between matrix operations (which you were incorrectly using) and array operations (which you should be using) is critical for writing MATLAB code.
Note that square brackets around one vector/matrix/scalar/array do nothing, get rid of them.
IdealGasLaw(1, 300, 1:4) % got rid of those pointless square backets
% and here we use array operations, not matrix operations.
function [p_Ideal, p_Waals] = IdealGasLaw(n, T, V)
R = 0.08206;
a = 1.39;
b = 0.0391;
p_Ideal = (n*R*T) ./ V;
p_Waals = ((n*R*T)./(V-n*b)) - ((n^2)*a)./V.^2;
end
Tip: if you are not doing linear algebra, you probably should be using array operations.
2 Commenti
Stephen23
il 1 Ott 2022
The assignment specifies that the function should have three outputs, but your function only returns two outputs (and those are not even in the right output positions).You need to provide exactly the outputs requested by the assignment, perhaps something like this:
[out, mx_err, at_vol] = IdealGasLaw(1, 300, 1:4)
function [output, max_error, at_volume] = IdealGasLaw(n, T, V)
R = 0.08206;
a = 1.39;
b = 0.0391;
p_Ideal = (n*R*T) ./ V; %ideal gas over array V
p_Waals = ((n*R*T)./(V-n*b)) - ((n^2)*a)./V.^2; %waals over array V
%
error = (p_Ideal - p_Waals)./(p_Waals); % percent error over array V
output = [V(:), p_Ideal(:), p_Waals(:), error(:)]; %output array with same number of rows as V
[max_error, idx_of_max] = max(error); %location of maximum error value
at_volume = V(idx_of_max); %volume corresponding to max error
end
Vedere anche
Categorie
Scopri di più su Linear Algebra in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!