所以我有两个组成的.m文件。这是我遇到的问题的一个例子,数学是伪数学
rectangle.m:
function [vol, surfArea] = rectangle(side1, side2, side3)
vol = ...;
surfArea = ...;
end
ratio.m:
function r = ratio(f,constant)
% r should return a scaled value of the volume to surface area ratio
% based on the constant provided.
% This line doesn't work but shows what I'm intending to do.
[vol,surfArea] = f
r = constant*vol*surfArea;
end
我不确定怎么办是将矩形函数作为f传递,然后从比率函数中访问vol和surfArea。我已经阅读了有关函数句柄和函数函数的Mathworks页面,并且已经空手而归,想出如何执行此操作。我是MATLAB的新手,所以这也无济于事。
如果您需要更多信息,请告诉我。
谢谢!
答案 0 :(得分:2)
传递函数rectangle
和ratio
参数的正确方法是
r = ratio( @recangle, constant )
然后,您可以在[vol,surfArea] = f(s1,s2,s3)
内拨打ratio
,但需要知道sideX
个参数。
如果ratio
不需要知道这些参数,那么您可以创建一个对象函数并将其作为参考参数传递。或者更好的是,你可以创建一个矩形类:
classdef Rectangle < handle
properties
side1, side2, side3;
end
methods
% Constructor
function self = Rectangle(s1,s2,s3)
if nargin == 3
self.set_sides(s1,s2,s3);
end
end
% Set sides in one call
function set_sides(self,s1,s2,s3)
self.side1 = s1;
self.side2 = s2;
self.side3 = s3;
end
function v = volume(self)
% compute volume
end
function s = surface_area(self)
% compute surface area
end
function r = ratio(self)
r = self.volume() / self.surface_area();
end
function r = scaled_ratio(self,constant)
r = constant * self.ratio();
end
end
end
答案 1 :(得分:1)
虽然我在上面的问题中没有提到这一点,但这正是我所寻找的。 p>
所以我想要做的是将一些矩形参数传递给ratio,同时能够在ratio函数中操作任意选定数量的矩形参数。鉴于我上面的.m文件,第三个.m看起来像这样。此解决方案最终使用MATLAB's anonymous functions。
<强> CalcRatio.m:强>
function cr = calcRatio(length)
% Calculates different volume to surface area ratios given
% given different lengths of side2 of the rectangle.
cr = ratio(@(x) rectangle(4,x,7); %<-- allows the 2nd argument to be
% manipulated by ratio function
end
<强> ratio.m:强>
function r = ratio(f,constant)
% r should return a scaled value of the volume to surface area ratio
% based on the constant provided.
% Uses constant as length for side2 -
% again, math doesnt make any sense, just showing what I wanted to do.
[vol,surfArea] = f(constant);
r = constant*vol*surfArea;
end