Unable to use mod function on cell array

5 ビュー (過去 30 日間)
Joel Abrahams
Joel Abrahams 2017 年 7 月 19 日
回答済み: Guillaume 2017 年 7 月 19 日
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.

採用された回答

dbmn
dbmn 2017 年 7 月 19 日
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 件のコメント
Joel Abrahams
Joel Abrahams 2017 年 7 月 19 日
Ah yes num2cell was the missing piece, thank you!

サインインしてコメントする。

その他の回答 (1 件)

Guillaume
Guillaume 2017 年 7 月 19 日
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.

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by