在Matlab中将单元格数组的部分与因子相乘

Multiply parts of cell array with factor in Matlab

我想在 Matlab 中乘以元胞数组的各个部分(参见下面的示例)。

my_cell1 = {'a', 'b', 'c'; 'd', '1', '2'; 'e', '3', '4'};
% Looks like:
% a b c
% d 1 2
% e 3 4
my_cell2 = my_cell1;
my_cell2(2:3, 2:3) = num2cell(str2double(my_cell2(2:3, 2:3)) * 2); %Multiply the numbers by factor 2
my_cell3 = {'a', 'b', 'c'; 'd', '2', '4'; 'e', '6', '8'};
isequal(my_cell2, my_cell3) %False

显然,my_cell2 不等于 my_cell3。情况似乎是这样,因为 my_cell2 中的数字现在是双倍的,而不是 strings/characters 了。但是,当我尝试将它们用作字符串时,出现错误:

my_cell2 = my_cell1;
my_cell2(2:3, 2:3) = num2str(str2double(my_cell2(2:3, 2:3)) * 2); %Error: Conversion to cell from char is not possible.

如何乘以 my_cell2 使其最后等于 my_cell3

使用 cellfun 添加一个中间步骤,将 str2num 应用于(子)元胞数组中的每个元胞:

my_cell1 = {'a', 'b', 'c'; 'd', '1', '2'; 'e', '3', '4'};

my_cell2 = my_cell1;
my_cell2(2:3, 2:3) = num2cell(str2double(my_cell2(2:3, 2:3)) * 2);
my_cell2(2:3, 2:3) = cellfun(@(x) num2str(x), my_cell2(2:3, 2:3), 'UniformOutput', false);

my_cell3 = {'a', 'b', 'c'; 'd', '2', '4'; 'e', '6', '8'};

isequal(my_cell2, my_cell3) % true

由于您的初始 "numerical" 数据(也)表示为字符数组,因此您始终需要正确转换为数值。如果您的数据实际上是数字,则可以最小化这种方法:

my_cell1 = {'a', 'b', 'c'; 'd', 1, 2; 'e', 3, 4};   % Note the difference here

my_cell2 = my_cell1;
my_cell2(2:3, 2:3) = cellfun(@(x) 2*x, my_cell2(2:3, 2:3), 'UniformOutput', false);

my_cell3 = {'a', 'b', 'c'; 'd', 2, 4; 'e', 6, 8};   % Note the difference here

isequal(my_cell2, my_cell3) % true

我找不到通过my_cell2{2:3, 2:3}直接访问和操作相应范围内元胞数组值的方法。也许,其他人对此有想法。

希望对您有所帮助!


免责声明:已使用 Octave 5.1.0 进行测试,但也适用于 MATLAB Online。