角落案例,意外和不寻常的 MATLAB [英] Corner Cases, Unexpected and Unusual MATLAB

查看:24
本文介绍了角落案例,意外和不寻常的 MATLAB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多年来,在阅读其他代码的过程中,我遇到并收集了一些 MATLAB 语法示例,这些示例起初可能不寻常且违反直觉.请随时评论或补充此列表.我用r2006a验证过.

Over the years, reading others code, I encountered and collected some examples of MATLAB syntax which can be at first unusual and counterintuitive. Please, feel free to comment or complement this list. I verified it with r2006a.

MATLAB 总是 将函数的第一个输出参数(如果它至少有一个)返回到它的调用者工作区,如果函数被调用而没有返回参数,例如 myFunc1();myFunc2(); 调用者工作区仍将包含 myFunc2(); 作为不可见"ans 变量的第一个输出.如果 ans 是引用对象,它可能会发挥重要作用 - 它会保持活动状态.

MATLAB always returns first output argument of a function (if it has at least one) into its caller workspace, also unexpectedly if function is being called without returning arguments like myFunc1(); myFunc2(); the caller workspace still would contain first output of myFunc2(); as "invisible" ans variable. It could play an important role if ans is a reference object - it would remain alive.

set([], 'Background:Color','red')

MATLAB 有时非常宽容.在这种情况下,为对象数组设置属性也适用于无意义的属性,至少在数组为空时是这样.这样的数组通常来自harray = findobj(0,'Tag','NotExistingTag')

MATLAB is very forgiving sometimes. In this case, setting properties to an array of objects works also with nonsense properties, at least when the array is empty. Such arrays usually come from harray = findobj(0,'Tag','NotExistingTag')

myArray([1,round(end/2)])

end 关键字的这种用法可能看起来不干净,但有时比使用 length(myArray) 非常方便.

This use of end keyword may seem unclean but is sometimes very handy instead of using length(myArray).

any([]) ~= all([])

意外地any([]) 返回false 并且all([]) 返回true.而且我一直认为 allany 强.

Surprisigly any([]) returns false and all([]) returns true. And I always thought that all is stronger then any.

with not empty 参数 all()any() 的值子集返回 true返回 true(例如真值表).这意味着 any() false 意味着 all() false.MATLAB 以 [] 作为参数违反了这个简单的规则.

with not empty argument all() returns true for a subset of values for which any() returns true (e.g. truth table). This means that any() false implies all() false. This simple rule is being violated by MATLAB with [] as argument.

洛伦也在博客上写过.

Select(Range(ExcelComObj))

程序风格的 COM 对象方法分派.不要奇怪 exist('Select') 返回零!

Procedural style COM object method dispatch. Do not wonder that exist('Select') returns zero!

[myString, myCell]

在这种情况下,MATLAB 将字符串变量 myString 隐式转换为单元格类型 {myString}.它有效,如果我不希望它这样做.

MATLAB makes in this case an implicit cast of string variable myString to cell type {myString}. It works, also if I would not expect it to do so.

[double(1.8), uint8(123)] => 2 123

另一个演员表示例.每个人都可能希望 uint8 值被转换为 double 但 Mathworks 有另一种看法.如果没有警告,这种行为是非常危险的.

Another cast example. Everybody would probably expect uint8 value being cast to double but Mathworks have another opinion. Without a warning this behavior is very dangerous.

a = 5;
b = a();

看起来很傻,但你可以用圆括号调用变量.实际上这是有道理的,因为这样您就可以执行给定句柄的函数.

It looks silly but you can call a variable with round brackets. Actually it makes sense because this way you can execute a function given its handle.

语法 Foo(:) 不仅适用于数据,还适用于以 Bar.Foo(:) 调用的函数,在这种情况下,传递函数输入参数作为字符 冒号 ':'.

Syntax Foo(:) works not only on data but also with functions if called as Bar.Foo(:), in this scenario the function input argument is passed as char colon ':'.

例如让 Bar.Foo = @(x) disp(x)现在调用 Bar.Foo(:) 在 MATLAB 命令行窗口中打印 char ':'.

For example let Bar.Foo = @(x) disp(x) Now calling Bar.Foo(:) prints char ':' in the MATLAB Command Window.

这个奇怪的功能适用于所有 MATLAB 7 版本,没有警告.

This strange feature works with all MATLAB 7 versions without warnings.

a = {'aa', 'bb'
'cc', 'dd'};

令人惊讶的是,这段代码既不返回向量也不引发错误,而是定义了矩阵,仅使用代码布局.应该是远古遗物.

Surprsisingly this code neither returns a vector nor rises an error but defins matrix, using just code layout. It is probably a relict from ancient times.

非常方便的功能,请参阅 gnovice 的评论.

very handy feature, see the comment by gnovice.

set(hobj, {'BackgroundColor','ForegroundColor'},{'red','blue'})

此代码执行您可能期望它执行的操作.该函数 set 接受一个结构体,因为它的第二个参数是一个已知事实并且是有意义的,而这个语法只是一个 cell2struct 外.

This code does what you probably expect it to do. That function set accepts a struct as its second argument is a known fact and makes sense, and this sintax is just a cell2struct away.

等价规则有时起初是出乎意料的.例如 'A'==65 返回 true(尽管对于 C 专家来说这是不言而喻的).同样,isequal([],{}) 返回,如预期的那样,falseisequal([],'') 返回 true.

Equvalence rules are sometimes unexpected at first. For example 'A'==65 returns true (although for C-experts it is self-evident). Similarly isequal([],{}) retuns, as expected, false and isequal([],'') returns true.

字符串数字等价意味着所有字符串函数也可用于数字数组,例如在大数组中查找子数组的索引:

The string-numeric equivalence means that all string functions can be used also for numeric arrays, for example to find indices of a sub-array in a large array:

ind = strfind( [1 2 3 4 1 2 3 4 1 2 3 4 ], [2 3] )

<小时>

MATLAB 函数 isnumeric() 为布尔值返回 false.这感觉只是......假:-)


MATLAB function isnumeric() returns false for booleans. This feels just ... false :-)

您还知道哪些意外/不寻常的 MATLAB 功能?

About which further unexpected/unusual MATLAB features are you aware?

推荐答案

图像坐标 vs 绘图坐标 每次都用来搞定.

%# create an image with one white pixel
img = zeros(100);
img(25,65) = 1;

%# show the image
figure
imshow(img);

%# now circle the pixel. To be sure of the coordinate, let's run find
[x,y] = find(img);
hold on
%# plot a red circle...
plot(x,y,'or')
%# ... and it's not in the right place

%# plot a green circle with x,y switched, and it works
plot(y,x,'og')

编辑 1

数组维度

变量至少有两个维度.标量大小为 [1,1],向量大小为 [1,n][n,1].因此,ndims 为它们中的任何一个返回 2(实际上,ndims([]) 也是 2,因为 size([])[0,0]).这使得测试输入的维度有点麻烦.要检查一维数组,您必须使用isvector,0D 数组需要isscalar.

Variables have at least two dimensions. Scalars are size [1,1], vectors are size [1,n] or [n,1]. Thus, ndims returns 2 for any of them (in fact, ndims([]) is 2 as well, since size([]) is [0,0]). This makes it a bit cumbersome to test for the dimensionality of your input. To check for 1D arrays, you have to use isvector, 0D arrays need isscalar.

编辑 2

数组赋值

通常,Matlab 对数组赋值很严格.例如

Normally, Matlab is strict with array assignments. For example

m = magic(3);
m(1:2,1:3) = zeros(3,2);

抛出一个

??? Subscripted assignment dimension mismatch.

但是,这些工作:

m(1:2,1:2) = 1; %# scalar to vector
m(2,:) = ones(3,1); %# vector n-by-1 to vector 1-by-n (for newer Matlab versions)
m(:) = 1:9; %# vector to 'linearized array'

编辑 3

使用错误大小的数组进行逻辑索引祝调试好运!

逻辑索引似乎调用了 find,因为您的逻辑数组不需要与索引相同数量的元素!

Logical indexing seems to make a call to find, since your logical array doesn't need the same amount of elements as there are indices!

>> m = magic(4); %# a 4-by-4 array
>> id = logical([1 1 0 1 0])
id =
     1     1     0     1     0
>> m(id,:)  %# id has five elements, m only four rows
ans =
    16     2     3    13
     5    11    10     8
     4    14    15     1
%# this wouldn't work if the last element of id was 1, btw

>> id = logical([1 1 0])
id =
     1     1     0
>> m(id,:) %# id has three elements, m has four rows
ans =
    16     2     3    13
     5    11    10     8

这篇关于角落案例,意外和不寻常的 MATLAB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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