我希望从零大小的矩阵开始,并根据方向选择继续在左侧或右侧分配列(总是固定的行数)。
我正在考虑的一些选项是:
1)沿正确方向生长矩阵,然后使用循环移位。但是,如果我这样做,我需要将新矩阵与具有不同列数的现有矩阵进行或。
所以在这种情况下,我需要找到一种简单的方法来对两个不等维的矩阵进行OR运算,我不知道。
2)不知怎的(我还不知道怎么样)我可以在Matlab中自动展开矩阵的左侧,就像Matlab支持右边的矩阵扩展一样,只需通过赋值超出范围。
注意:我不想在我的情况下使用填充,它会导致很多if-else块。
例如
mat = [1 2 3; 4 5 6; 7 8 9]
如果留下方向并且
new_mat = [10 11; 12 13; 14 15]
appended_mat = [10 11 1 2 3; 12 13 4 5 6; 14 15 7 8 9]
请帮帮我。
感谢。
答案 0 :(得分:3)
假设你有现有的矩阵
mat = [1 2 3; 4 5 6; 7 8 9]
并且您希望在左侧或右侧包含新行(长度相等),例如
new_mat = [10 11; 12 13; 14 15]
您可以使用以下方法将它们组合在一起:
appended_mat = [new_mat mat]
给你
appended_mat =
10 11 1 2 3
12 13 4 5 6
14 15 7 8 9
答案 1 :(得分:2)
以下是此问题的简单一行解决方案:
假设您有两个矩阵'old'和'new',direction
1如果正确,则0如果离开。
[old new]*direction + [new old]*~direction
答案 2 :(得分:1)
你可以写一个像这样的小函数:
function [ B ] = appendLR( A,newCol,direction )
Z{1,2} = A;
Z{1,2+direction} = newCol;
B = cell2mat(Z);
end
方向可以是1
,可以在右边添加,也可以在左侧-1
。
示例:
A = reshape(1:30,5,6);
1 6 11 16 21 26
2 7 12 17 22 27
3 8 13 18 23 28
4 9 14 19 24 29
5 10 15 20 25 30
newCol = 42*ones(5,1);
42
42
42
42
42
最后:
B = appendLR(A,newCol,-1)
42 1 6 11 16 21 26
42 2 7 12 17 22 27
42 3 8 13 18 23 28
42 4 9 14 19 24 29
42 5 10 15 20 25 30
newCol
也可以是矩阵,如上所述!
替代解决方案:
function [ B ] = appendLR( A,newCol,direction )
Z = [A newCol];
B = circshift(Z,[0,direction<0]);
end
同样有效。
答案 3 :(得分:1)
好的,我喜欢挑衅:)
%// Your matrices
mat = [1 2 3; 4 5 6; 7 8 9];
new_mat = [10 11; 12 13; 14 15];
%// You can of course re-define everything, such that your matrices are
%// defined as in this cell-array:
mats = {mat new_mat};
%// Set the direction
direction = 1; %// '1' for append to-the-right
%//direction = 2; %// '2' for append to-the-left
%// Auxiliary cell array, needed to avoid 'if-else'
directions = {1:size(mats,2) size(mats,2):-1:1};
%// or, if you wrap this in a function which concatenates just 2 matrices:
%// directions = {[1 2] [2 1]};
%// The actual concatentation
appended_mat = horzcat(mats{directions{direction}})
但是,老实说,我建议你只使用if-else
构造。这个技巧很好(就像thewaywewalk的功能,给你先生+1),但是它们是狭窄的,扭曲的,扭曲的,丑陋的,低效的,过于复杂的,难以维护的等等。等方法来解决你构成的看似任意的约束不使用if-else
。您想要完成的任务可以通过if-else
简单而优雅地完成。如果你不这么认为,我smell trouble;那么你当前的方法可能存在更深层次的问题。
答案 4 :(得分:0)
您可以尝试使用这样的函数句柄:
mat = [1 2 3; 4 5 6; 7 8 9]
new_mat = [10 11; 12 13; 14 15]
right = @(a,b) [a,b]
left = @(a,b) [b,a]
choice = right;
result_mat = choice(mat,new_mat)
当然你仍然需要做出选择...