필터 지우기
필터 지우기

Unable to use mod function on cell array

조회 수: 1 (최근 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 CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by