【问题标题】:How to create matrix in matlab that adds cells horizontally如何在matlab中创建水平添加单元格的矩阵
【发布时间】:2021-06-12 19:40:27
【问题描述】:

我想创建一个矩阵,例如 1xn,其中 n 由另一个输入确定。 例如,我有以下内容:

Example = [3 5 7 9];
New_matrix =  [int_col(Example (1)) int_col(Example (2)) int_col(Example (3)) int_col(Example (4))]; 

这个 New_matrix 就是我想要的输出。

但是,对于我的实际数据输入,我的示例矩阵是 1x47。 我怎样才能把它放在一个 for 循环中,以便它为所有长度示例提供 1 到指定数字的输出?(也保持水平)

这里添加了我使用的帮助功能:


% Helper function added as well 
function v = int_col(n)
v = zeros(1,n);
for index=1:n
   val = randi(n);
   while (val == index || any(val == v))
       val = randi(n);
       if (index == n && (any(v == n) ~= 1))
           val = n;
           break
       end
   end
   v(index) = val;
   if (index == n && val == n)
%       v(n) = v(n-1);
%       v(n-1) = n;
   end
   if n == 1 
       v = 1;
   end
end
v = v';
v = (sortrows(v))';
end

【问题讨论】:

  • 根据您的第一个示例,您只需要linear indexing:new_matrix = int_col(Example)。您问题的第二部分不清楚。

标签: arrays matlab for-loop matrix


【解决方案1】:

您是否尝试在int_col() 中重新实现randperm()?我不确定在每一列上分别运行 sortrows() 的目的是什么,但我想这可能是你想要的:

% Make up vector of column lengths
Example=randi(60,[1 47]);

% Create matrix
New_matrix=nan([max(Example) numel(Example)]);
for i=1:numel(Example)
  New_matrix(1:Example(i),i)=randperm(Example(i));
end

% Sort matrix rows from left to right
New_matrix=sortrows(New_matrix);

请注意,矩阵中的所有列必须具有相同数量的条目,因此您需要用一些值填充较短的列;一个典型的选择是 NaN,它被 sortrows() 和其他一些函数视为特殊值。

~

如果我的猜测不正确,而您的代码确实是目前的样子,您只需要:

New_matrix=[];
for i=1:numel(Example)
  New_matrix=[New_matrix 1:Example(i)];
end

在每次迭代中更改 New_matrix 的大小通常不是好的做法,但对于 47 次迭代来说,这应该没问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    相关资源
    最近更新 更多