极端情况,意外情况和不常见的MATLAB [英] Corner Cases, Unexpected and Unusual MATLAB

查看:76
本文介绍了极端情况,意外情况和不常见的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.

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.

Loren还过程样式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(:)),在这种情况下,函数输入参数作为char 冒号 ':'传递.

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?

推荐答案

图像坐标与绘图坐标每次都可以帮助我.

%# 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(实际上,由于size([])[0,0],因此ndims([])也为2).这使得测试输入的维数变得有些麻烦.要检查一维数组,必须使用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.

但是,这些方法可以工作:

However, these work:

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天全站免登陆