在matlab中生成一个特定的矩阵

时间:2015-02-07 14:48:44

标签: matlab matrix bsxfun

我有矩阵:    x=[0 0 0;5 8 0; 7 6 0]

我想要矩阵:    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或其他任何方式执行此操作?

2 个答案:

答案 0 :(得分:0)

根据我的理解,您可以使用repmatkron

来实现
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

答案 1 :(得分:0)

假设以下两个假设,您可以尝试其后列出的方法 -

  1. 继续adding而不是multiplying
  2. column-3中的所有最终元素,至少要达到72
  3. 方法#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