Data types of arrays in a function

조회 수: 1 (최근 30일)
Samuel Katongole
Samuel Katongole 2020년 7월 6일
댓글: Samuel Katongole 2021년 7월 20일
Hey,
I am trying to create a function that takes an array as an input arg and returns another array as output arg which should be if all elements of the input array are within the range of int8 is an int8, otherwise, it is the same type as the input array...The function is called as B=safe_int8(A).
I am using the following loop....
B=zeros(size(A)); % Pre-allocation since B changes size
for ii=1:size(A,1)
for jj=1:size(A,2)
if -128<A(ii,jj)&& A(ii,jj)<127
A=int8(A);
B=A;
else
B=(A);
end
end
end
Running it yields for instance
>> A=[1 0 3;4 5 6];
>> B=safe_int8(A)
B =
2×3 int8 matrix
1 0 3
4 5 6
>> A=[1 0 345;4 5 6];
>> B=safe_int8(A)
B =
2×3 int8 matrix
1 0 127
4 5 6
>> A=[1 1.05 3;4 5 6];
>> B=safe_int8(A)
B =
2×3 int8 matrix
1 1 3
4 5 6
Of course, the first trial gives the right answer; but the second and third which should give the class for B as double are instead returning it as an int8...How do i correct this?

답변 (2개)

madhan ravi
madhan ravi 2020년 7월 6일
if all((-128<=A)& (A<=127))
A=int8(A);
B=A;
else
B=(A);
end
Loops are not necessary here.

Stephen23
Stephen23 2020년 7월 7일
편집: Stephen23 2020년 7월 7일
B = int8(A);
if any(B(:)~=A(:))
B = A;
end
Note that this is a more versatile approach because it does not use hard-coded values, i.e. you can trivially change only the type conversion function and it will work. The type conversion function could even be a function handle.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by