What is the difference between the statements: A=2; A=(2); A=[2]?

3 ビュー (過去 30 日間)
edvyan
edvyan 2011 年 9 月 5 日
I am a beginner, got a question about it When making an assignment, it usually uses A=2, and it is also understandable that A=[2] as matrix form. But what's the point of A=(2) here that returns the same value? it works when I am trying to change a value to a matrix.
  3 件のコメント
edvyan
edvyan 2011 年 9 月 5 日
For a created matrix, i.e. A=[1 2 3;4 5 6], if I want to change the element 2 to 8, we normally use A(2)=8 or uncommonly A(2)=[8]. But why A(2)=(8) returns the same answer [1 2 3;8 5 4] rather than an error notice?
Paulo Silva
Paulo Silva 2011 年 9 月 5 日
It depends where the parenthesis are located on the expression, if you put the ( after the variable it means you are going to insert index or indices values, if you put ( after the equal it will be ignored.

サインインしてコメントする。

回答 (2 件)

Paulo Silva
Paulo Silva 2011 年 9 月 5 日
In MATLAB values like [2] and (2) are the same as 2, for the ( type they mean other things when used after a variable or function.
now for more values
A=[1 2 3] %same as A=1:3
A is now a vector and if you do A(2) you get the second value of the vector A which is 2
  2 件のコメント
Oleg Komarov
Oleg Komarov 2011 年 9 月 5 日
The square brackets should cause a small overhead for calling the concatenation.
Teja Muppirala
Teja Muppirala 2011 年 9 月 5 日
When used in loop indices, square brackets will make things very slow:
%% Very fast
tic
x = 0;
for n = 1:1e6
x = x+1;
end
x
toc
%% Very slow
tic
x = 0;
for n = [1:1e6]
x = x+1;
end
x
toc

サインインしてコメントする。


Fangjun Jiang
Fangjun Jiang 2011 年 9 月 5 日
To merely answer your question.
A=2 is the same as A=[2], is because 2 is a special case of a matrix with size as 1x1.
A=2 is the same as A=(2), is because 2 can be regarded as a special case of an calculation, for example, it could be A=(4-3)*2
You may want to learn other use of (),{} and [] in MATLAB. Type 'help {' to see a list of symbols and their use.

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by