Matlab:不正确的索引矩阵参考(或优于Matlab) [英] Matlab: Improper index matrix reference (or outsmarting matlab)

查看:149
本文介绍了Matlab:不正确的索引矩阵参考(或优于Matlab)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在Matlab中编写茉莉花之类的测试. 所以像

I want to be able to write jasmine-like tests in Matlab. So something like

expect(myfibonacci(0)).toBe(0);
expect(myfibonacci(5)).toBe(15);
expect(myfibonacci(10)).toBe(55);

我尝试实现以下两种策略:

There are two strategies I tried to implement this:

(1)第一个策略使用结构

expect = @(actual_value) struct('toBe', @(expected_value) assert(actual_value == expected_value));

(真正的实现方式不只是调用assert)

(The real implementation will not just call assert)

但是这不起作用:

expect(1).toBe(1); % this triggers a syntax error
??? Improper index matrix reference.

% this will work:
x = expect(1);
x.toBe(1);

(2)我尝试的第二种策略是使用类:

(2) The second strategy I tried is using a class:

classdef expect
properties (Hidden)
    actual_value
end

methods
    function obj = expect(actual_value)
        obj.actual_value = actual_value;
    end

    function obj = toBe(obj, expected_value)
        assert(obj.actual_value == expected_value);
    end
end
end

乍一看,这看起来不错: 您可以在控制台中运行

At first glance this looks fine: You can run in the console

expect(1).toBe(1);

但是,在控制台中而不是在脚本中运行

However, running this not in the console but in a script gives

??? Static method or constructor invocations cannot be indexed.
Do not follow the call to the static method or constructor with
any additional indexing or dot references.

Error in ==> test at 1
expect(1).toBe(1);

这里是否有任何方法可以使这个想法在matlab中发挥作用?

Is here any way to make this idea work in matlab at all?

推荐答案

这是一个带有重载subsref方法的示例实现. 我猜也可以只用一个类来完成,但这会使subsref-overloading更加难看.

Here's an examplary implementation with an overloaded subsref method. It could also be done with only one class I guess, but that would make the subsref-overloading even uglier.

classdef Tester < handle
    methods
        function obj = Tester()
        end

        function [varargout] = subsref(this,S)

            if S(1).type(1) =='('
                tv = TestValue(S(1).subs{:});
            end

            if numel(S) > 1
                try
                    [varargout{1:nargout}] = builtin('subsref', tv, S(2:end));
                catch me
                    me.throwAsCaller();
                end
            else
                varargout{1} = tv;
            end

        end
    end
end

还有

classdef TestValue 
    properties (Hidden)
        value;
    end
    methods
        function this = TestValue(value)
            this.value = value;
        end

        function toBe(this, v)
            assert( isequal(this.value, v) );
        end
    end
end

结果:

>> expect(1).toBe(1)
>> expect(1).toBe(2)
Error using TestValue/toBe (line 13)
Assertion failed.

这篇关于Matlab:不正确的索引矩阵参考(或优于Matlab)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆