# I am trying to get a 3*3 diagnol matrix by using the following code. But the resultant matrix dimensions exceed 3*3 matrix.

1 次查看（过去 30 天）
Ameer Hamza 2018-5-6

theta = 0:pi:2*pi;
a = cos(theta)+sin(theta);
A = ismatrix([[a,0,0],[0,a,0],[0,0,a]]);
a = cos(theta)+sin(theta);
A = ismatrix([[a,0,0],[0,a,0],[0,0,a]]);
B = [a 0 0;0 a 0;0 0 a];
##### 3 个评论显示 2更早的评论隐藏 2更早的评论
Stephen23 2018-5-6

@Ameer Hamza: The point of my comment is that your code does not create a matrix.

### 回答（1 个）

Ameer Hamza 2018-5-6

If you want the element of a to be the diagonal of B, you need something like this
theta = 0:pi:2*pi;
a = cos(theta)+sin(theta);
B = diag(a);
##### 4 个评论显示 3更早的评论隐藏 3更早的评论
Ameer Hamza 2018-5-6
In that video, for loop is used. In my code there is not for loop and MATLAB does store all the values of a. Have you tried running the code? The following code gives a vector (containing all values of a)
theta = 0:pi:2*pi;
a = cos(theta)+sin(theta);
disp(theta);
ans =
0 3.1416 6.2832
disp(a);
ans =
1 -1 1
You still did not explain, what do you want in MATRIX?

### 类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

### Community Treasure Hunt

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

Start Hunting!