Filter löschen
Filter löschen

Unable to use mod function on cell array

1 Ansicht (letzte 30 Tage)
Joel Abrahams
Joel Abrahams am 19 Jul. 2017
Beantwortet: Guillaume am 19 Jul. 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.

Akzeptierte Antwort

dbmn
dbmn am 19 Jul. 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 Kommentar
Joel Abrahams
Joel Abrahams am 19 Jul. 2017
Ah yes num2cell was the missing piece, thank you!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Guillaume
Guillaume am 19 Jul. 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.

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by