Setting the last value of each matrix in an array of cells in Matlab

I have an array of cells where each cell contains a matrix of the same size. How to efficiently set the last record of each matrix in an array? I tried to use cellfun, but it doesn't seem like an assignment is possible.

A minimal working example (the most efficient implementation I could come up with):

C = cell(5, 6, 7);
[C{:}] = deal(ones(10, 1));
for i = 1:5
    for j = 1:6
        for k = 1:7
            C{i,j,k}(end) = 0;
        end
    end
end
+4
source share
2 answers

Option 1

Create a function (e.g. in a separate file)

function x = assignAtEnd(x, v)
  x(end) = v;
end

and do cellfunas follows

B = cellfun(@(x) assignAtEnd(x, 0), C, 'UniformOutput', false);

This will give you an array of cells Bwith all values ​​at the end changed to 0.

, , , for. . 1.000.000 (100, 100, 100),

for-loop (3D): 3.48 sec
for-loop (1D as per @mikkola): 2.67 sec
cellfun: 3.06 sec

2

, , , , .

% creating the cell
cellDim = 100;
matrixDim = 10;
C = cell(cellDim, cellDim, cellDim);
[C{:}] = deal(1:matrixDim);

% converting to a 4D numeric matrix
A = reshape(cell2mat(C), cellDim, matrixDim, cellDim, cellDim);
% assigning the 0s
A(:,end,:,:) = 0;
% converting back to a cell
B = squeeze(num2cell(A, 2));

, .

with numeric conversion: 1.93 sec

1.40 sec , 0.5 sec, 5 !

@LuisMendo ,

with numeric conversion (@LuisMendo): 1.66 sec

, ! .

0

.

  • , ( , );
  • ( , ).

:

C = repmat({zeros(2,3)}, 4, 5, 6); % example cell array with matrices
values = 1:numel(C); % example vector with numel(C) values. Or it can be a scalar
t = cat(3, C{:}); % temporarily concatenate all matrices into 3D array
t(end,end,:) = values; % set last value of each matrix
C = reshape(num2cell(t, [1 2]), size(C)); % convert back

:

>> whos C
  Name      Size             Bytes  Class    Attributes

  C         4x5x6            19200  cell               

>> C{1,1,1}
ans =
     0     0     0
     0     0     1
>> C{2,1,1}
ans =
     0     0     0
     0     0     2
>> C{4,5,6}
ans =
     0     0     0
     0     0   120
0

Source: https://habr.com/ru/post/1680678/


All Articles