How can I generate a vector in a for loop with different sizes? In for iii, I used str2double(strrep(num2str(e), ' ','')) to store it. It worked. How can I get f to generate a stored vector if f = e ?
2 views (last 30 days)
Show older comments
% Problem 40. Reverse Run-Length Encoder
% x = 2, 5, 1, 2, 4, 1, 1, 3
% can be read as
% Two 5's, one 2, four 1's, one 3
% which translates to
% y = 5, 5, 2, 1, 1, 1, 1, 3
% So y is the reconstructed vector that corresponds to the counting
% sequence x. For this problem, all elements in the sequences x and y will
% be in the range from 1 to 9.
x =[ 2 5 1 2 4 1 1 3];
a = zeros(1,length(x));
b = zeros(1,length(x));
c = zeros(1,length(x));
f = [];
e = zeros(1,length(x));
for i = 1:2:length(x)
a(i) = x(i);
end
a = a; % Why does it have zeros in the vector? count
a(a==0) = [];
for ii = 2:2:length(x)
b(ii) = x(ii);
end
b = b; % zeros? numbers
b(b==0) = [];
% Join a and b.
for iii = 1:1:length(a)
c = a(iii); % count
d = b(iii); % number to repeat
e = repelem(d,c); % Repeats numbers
f(iii) = str2double(strrep(num2str(e), ' ','')); % removes the the spaces
end
format
g = num2str(f) - '0';
g(g == -16) = []; % Why are there -16 in the vector?
y = g;
end
1 Comment
Stephen23
on 31 Aug 2018
Edited: Stephen23
on 31 Aug 2018
"a = a; % Why does it have zeros in the vector?"
Because you define a to be all zeros, then in the loop you are allocating values into vector a at positions 1, 3, 5, 7,... of course the remaining positions 2, 4, 6,... remain zero, just as you defined them a few lines earlier. You defined them as zero, and did not change them to anything else... what value would you expect them to be?
Doing this with a loop is a waste of time anwyway, it is much simpler to use indexing:
a = x(1:2:end);
Ditto for b, using a loop is a waste of time, when simple indexing is faster, neater, and more efficient:
b = x(2:2:end);
No need to use loops with repelem, it works quite well with vectors.
"Why are there -16 in the vector?"
Because the space character ' ' has character code value 32. And then you subtract character '0' (which as code value 48), thus giving -16:
>> +'0'
ans = 48
>> +' '
ans = 32
>> ' '-'0'
ans = -16
>> 32-48
ans = -16
There are space character because num2str uses them as separators between the numbers represented in the char vector. All this switching between character and numeric representations is slow and unnecessary anyway, and gives an output which is class char, rather than numeric. Your code would be a lot simpler and more efficient if you did not convert to character anywhere: just stick to numeric data.
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!