Usage of square brackets in MATLAB

淺唱寂寞╮ 提交于 2021-01-27 07:40:28

问题


In MATLAB you can create an array of integers easily with

N = 100; % Number of points
A = 1:N; % row vector of 1,2,3,..., 100

If I want a column vector instead of a row vector, I can do that with

A = [1:N].';

Now, MATLAB warns me that

Use of brackets [] is unnecessary. Use parentheses to group if necessary.

Well, they are not unnecessary, because 1:N.' creates a row vector, as only the scalar N is transposed, as opposed to the full array.

I can of course suppress this message on that line, in that file, or in all files, but why does MATLAB throw this warning in the first place, as it seems that I can't do without those brackets in this case?

It turns out a large part of the confusion stems from the usage of American English by The MathWorks, as the rest of the English-speaking world uses the term brackets for () and the term square brackets for []. See Wikipedia


回答1:


As MATLAB warns you: Use parentheses to group if necessary. In your case it is necessary. You want .' to apply to 1:N, therefore use parentheses (). Square brackets [] are for collecting the elements within, but 1:N is already collected

A=(1:N).';



回答2:


The square brackets are used to declare arrays. However, MATLAB's syntax is built so that 1:n will already create an array.

[1:3] would then be equivalent to [[1 2 3]], which is why MATLAB's tells you that squares brackets are unnecessary in this case

This said, you definitely need to group your array declaration with parenthesis before transposing, due to operator precedence



来源:https://stackoverflow.com/questions/41038431/usage-of-square-brackets-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!