【问题标题】:Trouble converting floating decimal into integer无法将浮点小数转换为整数
【发布时间】:2018-06-07 02:25:58
【问题描述】:

我创建了一个用户定义的函数,其中输入是 j =indices,new_loc = 一个 51x2 的单元格位置矩阵,我的 51x2 矩阵的第一个列的大小 = 51。

function [x,y,w,z] = check_location(j,new_loc,size)

disp(j);
a = j / size + 1; %Finds 1st element of compared array
b = mod(j,size); %Finds 1st element of comparing array

int8(a) %Must be whole integer
int8(b) %" "

fprintf('a = %g',a)

if b == 0 %1st element cannot be 0
    b = b + 1;
else
    ;
end

fprintf('b = %g',b)

x = new_loc(a,1); % [x y]
y = new_loc(a,2);
w = new_loc(b,1); % [w z]
z = new_loc(b,2);

我很困惑,因为我用 fprintf 函数测试了我的输出,而 fprintf('a = %g',a) 显示的是十进制数,而 a = j / size + 1 正在评估一个整数。另外,我收到错误:下标索引必须是真正的正整数或逻辑。

for j = 1:numel(D)
    if D(j) < 8 & D(j) ~= 0
         [x1,y1,x2,y2] = check_location(j,new_location,numel(new_location(:,1)));
%         smallest_int = check_intensity(x1,y1,x2,y2,B); 
%         [row,col] = find(B == smallest_int) %Convert smallest_int vals w/ it's location
%         new_location(row,col) = []; %Check new_location w/ smallest_int vals and delete
    end
end

这是我正在测试我的函数的 for 循环。

【问题讨论】:

  • Barker 指出了您代码中的错误,但我也建议您不要转换为 int8。 MATLAB 的原生类型是double,任何其他类型在做算术时都会造成困难(和令人惊讶的结果)。使用floorfixa 转换为整数。 b 已经是一个整数。

标签: matlab


【解决方案1】:

这些行:

int8(a) %Must be whole integer
int8(b) %" "

两者都返回int8 值,但它们没有存储在任何地方,因此它们丢失了。您需要将整数值分配回原始变量。

a = int8(a) %Must be whole integer
b = int8(b) %" "

【讨论】:

    猜你喜欢
    • 2019-11-25
    • 2018-04-30
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多