Unable to use mod function on cell array

5 visualizaciones (últimos 30 días)
Joel Abrahams
Joel Abrahams el 19 de Jul. de 2017
Respondida: Guillaume el 19 de Jul. de 2017
Say I have cell array A with size 10x10.
I want to perform a modulo on the 6th column of A, which is all numbers.
I have tried the following:
A(:, 6) = arrayfun(@(x) mod(x, 80), A(:, 3));
But then I get the error:
Undefined function 'mod' for input arguments of type 'cell'.
I then tried the following:
A(:,6) = mod(A(:,6), 80);
But I still get the same error. How do I do this?
I have also tried using cellfun:
A(:, 6) = cellfun(@(x) mod(x, 80), A(:, 3));
But then I get the following error:
Conversion to cell from int64 is not possible.

Respuesta aceptada

dbmn
dbmn el 19 de Jul. de 2017
you try to convert a int/double to a cell
% Create random Variable A
A=num2cell(rand(10,10));
% check if your cellfun is working
tmp = cellfun(@(x) mod(x, 80), A(:, 3));
% it is! no errors, great
% now lets assign that thing to your cell
% do a quick check about the types
class(tmp)
class(A(:,6))
% Uh oh, double and cell - that assignment wont work. We need to convert
% try
A(:,6) = num2cell(tmp);
% that works
And now that we know that it works, we try to do it nicely
A(:, 6) = num2cell(cellfun(@(x) mod(x, 80), A(:, 3)));
  1 comentario
Joel Abrahams
Joel Abrahams el 19 de Jul. de 2017
Ah yes num2cell was the missing piece, thank you!

Iniciar sesión para comentar.

Más respuestas (1)

Guillaume
Guillaume el 19 de Jul. de 2017
Faster than using cellfun would be to convert the cell column to a matrix, perform the mod and convert back to a cell array:
A(:, 6) = num2cell(mod(cell2mat(A(:, 6)), 80));
On a large cell array, this probably is a lot faster.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by