# Using an array as an element in a function.

조회 수: 3(최근 30일)
Michael 2022년 10월 1일
댓글: Stephen23 2022년 10월 1일
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)

댓글을 달려면 로그인하십시오.

### 답변(1개)

Stephen23 2022년 10월 1일
편집: Stephen23 2022년 10월 1일
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
ans = 1×4
24.6180 12.3090 8.2060 6.1545
% 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표시숨기기 이전 댓글 수: 1
Stephen23 2022년 10월 1일
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)
out = 4×4
1.0000 24.6180 24.2297 0.0160 2.0000 12.3090 12.2069 0.0084 3.0000 8.2060 8.1599 0.0056 4.0000 6.1545 6.1284 0.0043
mx_err = 0.0160
at_vol = 1
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

댓글을 달려면 로그인하십시오.

### 범주

Find more on Matrix Indexing in Help Center and File Exchange

R2022b

### Community Treasure Hunt

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

Start Hunting!

Translated by