特定矩阵I具有矩阵: x=[0 0 0;5 8 0; 7 6 0]
生成在MATLAB
欲矩阵: m=[0 0 0;5 8 0;7 6 0; 0 0 8;5 8 8;7 6 8; 0 0 16;5 8 16;7 6 16]
我想,而其他两列保持相同的是矩阵x
的第三列得到由8各自时间乘以。我希望这样继续下去,直到第三列的值达到72为止。
我该怎么用bsxfun
或其他方式来做到这一点?
特定矩阵I具有矩阵: x=[0 0 0;5 8 0; 7 6 0]
生成在MATLAB
欲矩阵: m=[0 0 0;5 8 0;7 6 0; 0 0 8;5 8 8;7 6 8; 0 0 16;5 8 16;7 6 16]
我想,而其他两列保持相同的是矩阵x
的第三列得到由8各自时间乘以。我希望这样继续下去,直到第三列的值达到72为止。
我该怎么用bsxfun
或其他方式来做到这一点?
假设下面的两个假设,你可以尝试其后列出的方法 -
adding
而不是multiplying
。column-3
至少达到72
。方法#1随着bsxfun
]
stopn = 72; %// stop adding till this number
add_factor = 8; %// Add factor to be added at each iteration to get to 72
ntimes = ceil(max((stopn - x(:,3))/add_factor)) %// no. of iterations needed
%// Get the starting 2d version of matrix to be added to x iteratively
x_add_2d = zeros(size(x)); %//
x_add_2d(:,3) = add_factor;
%// Get the complete version of matrix to be added (in 3d), then add to x
x_add_3d = bsxfun(@plus,x,bsxfun(@times,x_add_2d,permute([0:ntimes],[1 3 2])))
%// Concatenate along rows to form a 2D array as the final output
out = reshape(permute(x_add_3d,[1 3 2]),size(x_add_3d,1)*(ntimes+1),[])
方法2 [附repmat
]
stopn = 72; %// stop adding till this number
add_factor = 8; %// Add factor to be added at each iteration to get to 72
ntimes = ceil(max((stopn - x(:,3))/add_factor)); %// no. of iterations needed
out = repmat(x,[ntimes+1 1]) %// replicated version of x
add_col3 = repmat([0:8:ntimes*8],size(x,1),1) %// column-3 values to be added
out(:,3) = out(:,3) + add_col3(:) %// add those for the final output
样品运行 -
x =
52 43 57
41 40 48
41 49 50
out =
52 43 57
41 40 48
41 49 50
52 43 65
41 40 56
41 49 58
52 43 73
41 40 64
41 49 66
52 43 81
41 40 72
41 49 74
明白了......感谢的人 – 2015-02-08 05:23:01
@SaurabhTariyal如果这回答了您的原始问题,请考虑通过点击旁边的空白复选标记来接受它。谢谢! – Divakar 2015-02-12 05:52:47
据我了解,你可以使用repmat
和kron
做到这一点:
clear
clc
x=[0 0 0;5 8 0; 7 6 0];
%// Generate last column containing the values form 0 to 72, each repeated 3 times.
y = kron(0:8:72,ones(1,3))
%// The first 2 columns remain the same, so we just repeat them 10 times.
out = [repmat(x(:,1:2),10,1) y(:)]
用方括号来连接,输出是这样的:
out =
0 0 0
5 8 0
7 6 0
0 0 8
5 8 8
7 6 8
0 0 16
5 8 16
7 6 16
0 0 24
5 8 24
7 6 24
0 0 32
5 8 32
7 6 32
0 0 40
5 8 40
7 6 40
0 0 48
5 8 48
7 6 48
0 0 56
5 8 56
7 6 56
0 0 64
5 8 64
7 6 64
0 0 72
5 8 72
7 6 72
感谢Benoit_11 – 2015-02-08 05:21:53
乘以8或加上8?而第3列中的哪个元素必须达到72,任何一个元素?它是否必须达到72,或可能达到*至少* 72?我认为更好的示例'x'将在第3列中使用不同的元素,而不是像所有的零。 – Divakar 2015-02-07 14:59:15
矩阵每重复一次,第三列必须加8,即达到72.也就是说,对于第一次重复,即第四行,第三列将是8 8 8。对于第七行,即第二次重复,第三列将是16 16 16,依此类推,直到列达到72. – 2015-02-08 05:57:54
你是否也可以回答我的第二个问题。如果我想在每个矩阵重复的情况下向第1列和第2列添加常数,该怎么办?也就是说,如果我要添加的常量是5,那么矩阵第二次重复中的第一列是5 10 12,第二列变成5 13 11.在第三次重复中,第一列变为10 15 17,第二列变为10 18 16等等。在这整个过程中,我的第三列继续增加8次(正如你已经回答的那样) – 2015-02-08 05:59:38