How to solve "Subscripted assignment dimension mismatch" error ?

2 次查看(过去 30 天)
Hi, I have 3 input which is 1 7 6 and the output supposed to be 00 for input 1, 110000 for input 7 and 1011 for input 6. my output supposed to be 001100001011 if it reads 1 7 6. But, this error "Subscripted assignment dimension mismatch" keeps appears. what should I do? please help me.Below are my coding
clear all
clc
i=1;
j=1;
p=1;
z=1;
input = [ 1 7 6 ];
for i=1:length(input)
if input(i) < 3 %level1
k = 1; %dec
h1 = 0 ;
h1(p) = dec2bin(h1,1);
t = input(i)-k ;
t1(z) = dec2bin(t,1);
huff(j) = [h1(p) t1(z)];
p=p+1
z=z+1
j=j+1;
elseif input(i) < 7 %level2
k = 3;
h1 = 2 ;
h1(p) = dec2bin(h1,2);
t = input(i)-k ;
t1(z) = dec2bin(t,2);
huff(j)= [h1(p) t1(z)];
p=p+1;
z=z+1;
j=j+1;
elseif input(i) < 15 %level3
k = 7;
h1 = 6 ;
h1(p) = dec2bin(h1,3);
t = input(i)-k ;
t1(z) = dec2bin(t,3);
huff(j) = [h1(p) t1(z)];
p=p+1;
z=z+1;
j=j+1;
end
end

回答(1 个)

Are Mjaavatten
Are Mjaavatten 2018-4-4
dec2bin(n,m) returns the binary representation of n as a string of m characters, with leading '0'-s as needed. When you assign a number to the variable h1 (e,g, h1 = 2) you tell Matlab that h1 is an array of doubles. The element h1(p) can then only hold a single double. You then try to assign a string of two or more characters to this element, which results in an error.
I fail to see the logic in what you are trying to do, but I have modified your code to give the result you specify. Instead of using indices in the character array huff (e.g. huff(j)) I extend it by concatenating more characters at the end. Note that your variables p, z, and j all take the same value as i, so they are superfluous.
input = [ 1 7 6 ];
huff = [];
for i=1:length(input)
if input(i) < 3 %level1
k = 1; %dec
h1 = dec2bin(0,1);
t = input(i)-k ;
t1 = dec2bin(t,1);
elseif input(i) < 7 %level2
k = 3;
h1 = dec2bin(2,2);
t = input(i)-k ;
t1 = dec2bin(t,2);
elseif input(i) < 15 %level3
k = 7;
h1 = dec2bin(6,3);
t = input(i)-k ;
t1 = dec2bin(t,3);
end
huff = [huff h1 t1];
end
disp(huff)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by