Produce a matrix with the class of its elements

4 ビュー (過去 30 日間)
Andreas Georgakarakos
Andreas Georgakarakos 2017 年 3 月 31 日
Input: 2-dimensional Matrix A
Output: Matrix B, having the same dimensions as A, where each element is the class of the corresponding element in A.
e.g. If A(1,1) = double, then B(1,1) = double
My code is as follows:
function B = whatclass(A)
[row,col] = size(A);
B = [];
for ii=1:row
for jj=1:col
B(ii,jj) = class(A(ii,jj));
end
end
end
I am getting the error below:
Assignment has more non-singleton rhs dimensions than non-singleton subscripts
Error in integerize (line 6) B(ii,jj) = class(A(ii,jj));
Any thoughts? Help in advance.

採用された回答

Stephen23
Stephen23 2017 年 4 月 1 日
Assuming that the input is a cell array (otherwise this task does not make much sense):
>> A = {double(1),single(2);uint8(3),int64(4)}
A =
[1] [2]
[3] [4]
>> B = cellfun(@class,A,'UniformOutput',false)
B =
'double' 'single'
'uint8' 'int64'

その他の回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2017 年 3 月 31 日
class(1) returns the string 'double'.
So you need to use B{ii,jj} = class(A(ii,jj))
  2 件のコメント
Andreas Georgakarakos
Andreas Georgakarakos 2017 年 4 月 1 日
Hi, thanks for your reply. Now, I am getting this error:
Cell contents assignment to a non-cell array object. Error in whatclass (line 6) B{ii,jj} = {class(A(ii,jj))};
Any ideas?
Andreas Georgakarakos
Andreas Georgakarakos 2017 年 4 月 3 日
Solved it, thanks a lot.

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by