创建一个矩阵,该矩阵在任意偏移对角线上 [英] Create a matrix with ones on any offset diagonal
问题描述
我的目标是创建一个在偏移对角线上带有矩阵的函数:
I'm aiming for a function that creates matrices with ones on offset diagonals:
与eye(5)
函数类似,但现在在对角线偏移上.最好不要使用双for
循环.我不需要完整的矩阵,而是必须将它们插入现有的矩阵中.我该怎么做?
So similar to the eye(5)
function, but now on offset diagonals. Preferably not using double for
loops. I do not want the full matrix, rather I have to insert them into an existing matrix. How can I accomplish this?
推荐答案
diag
内置了以下功能:
diag
has this functionality built in:
diag(ones(4,1),1)
ans =
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
0 0 0 0 0
diag(ones(4,1),-1)
ans =
0 0 0 0 0
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
diag(V,k)
的语法是:V
是要放在对角线上的向量(可以是1或任何奇数向量),而k
是对角线的标签. 0
是主对角线,正整数逐渐远离上对角线,负整数与下对角线相同;即k=1
给出了第一个上对角线,k=-4
给出了左下角.
Where the syntax of diag(V,k)
is: V
is the vector to be put on the diagonal (be it ones, or any odd vector), and k
is the label of the diagonal. 0
is the main diagonal, positive integers are increasingly further away upper diagonals and negative integers the same for the lower diagonals; i.e. k=1
gives the first upper diagonal, k=-4
gives the lower left corner in this example.
出于完整性考虑,如果您只希望索引而不是完整矩阵(因为您建议将向量插入当前矩阵),则可以使用以下函数:
For completeness, if you just want the indices instead of a full matrix (since you suggested you wanted to insert a vector into a present matrix) you can use the following function:
function [idx] = diagidx(n,k)
% n size of square matrix
% k number of diagonal
if k==0 % identity
idx = [(1:n).' (1:n).']; % [row col]
elseif k>0 % Upper diagonal
idx = [(1:n-k).' (1+k:n).'];
elseif k<0 % lower diagonal
idx = [(1+abs(k):n).' (1:n-abs(k)).'];
end
end
其中idx
的每一行都包含矩阵的索引.
where each row of idx
contains the indices for the matrix.
这篇关于创建一个矩阵,该矩阵在任意偏移对角线上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!