简体   繁体   English

Matlab 错误:下标赋值维度不匹配

[英]Matlab Error: Subscripted assignment dimension mismatch

I am trying to convert decimal number to binary.我正在尝试将十进制数转换为二进制数。 It works for regular decimal numbers.它适用于常规十进制数。 However, when I enter (25.10) I get the subscripted error.但是,当我输入 (25.10) 时,出现下标错误。

My code below.我的代码如下。

function [binary] = decimal2binary(decimal)
% floor : rounds towards minus infinity
% rem : remainder after division
% num2str : converts numbers to strings
% fliplr : flips string bits to get correct order
i = 1.0;
q = floor(decimal/2);
r = rem(decimal, 2);
% THIS IS WHERE THE ERROR OCCURS binary(i) = num2str(r(i));
while 2 <= q
    decimal = q;
    i = i+1;
    q = floor(decimal/2);
    r = rem(decimal, 2);
    binary(i) = num2str(r);
end
binary(i + 1) = num2str(q);
binary = fliplr(binary);
end

Assuming the line with the error is indeed:假设有错误的行确实是:

binary(i) = num2str(r(i));

Then, when calling the function with argument 25.10, before reaching this line we have:然后,当调用带有参数 25.10 的函数时,在到达这一行之前,我们有:

i=1
r=1.10000
num2str(r(i)) = '1.1'

That's why the attribution这就是为什么归因

 binary(i) = num2str(r(i));

Does not work.不起作用。 In Matlab, binary(1) is a 1x1 char array.在 Matlab 中, binary(1) 是一个 1x1 字符数组。 You are trying to fit a 1x3 char array ('1.1') to it.您正在尝试将 1x3 字符数组 ('1.1') 放入其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM