Clear Filters
Clear Filters

any suggestion to store answer after for loop into a matrix to use later?

1 view (last 30 days)
this is what i have so far, it only store the answer of the last entry of x (N) into matrix b, which was supposed to have all the binary entries for each entry of x (from 0 upto N). Any improvement I can make to achieve that?
function [x] = mybinplot(N)
x = 0:N;
for d = 0:N
if d == 0
b = 0;
else
p = 0;
while 2^p <= d
p = p + 1;
end
b = zeros(p,length(x));
power = p-1;
for ii = 1:length(b)
if d >= 2^power
b(ii) = 1;
d = d - 2^power;
end
power = power - 1;
end
end
end
z = fliplr(b);
disp(z)

Accepted Answer

Jan
Jan on 22 Mar 2021
Edited: Jan on 27 Mar 2021
x = 0:N;
b = zeros(ceil(log2(N)), length(x)); % Move this BEFORE the loop to avoid overwriting
for d = 1:N
p = 0;
while 2^p <= d
p = p + 1;
end
power = p-1;
for ii = 1:p
if d >= 2^power
b(ii, d + 1) = 1;
d = d - 2^power;
end
power = power - 1;
end
end
But the result looks strange:
b =
0 1 1 1 1 1
0 1 0 0 0 0
0 1 0 0 0 0
You forgot to mention, what your code should achieve.
By the way, v=ceil(log2(N)) is a vector. Then zeros(v, length(x)) is working, but a confusing exception. Better use the scalar ceil(log2(max(N))) .
[EDITED] Of course this works as good or bad as the original code also. I could not post a working version directly, because you did not explain, what you want to get. The actual question "store answer after for loop into a matrix to use later?" did not clarify this.
After reading your comment:
x = 0:5;
Len = ceil(log2(max(x)));
z = rem(floor(pow2(1-Len:0).' * x), 2);
Or with a loop:
x = 0:5;
Len = ceil(log2(max(x)));
b = zeros(Len, numel(x));
for k = Len:-1:1 % From bottom to top:
b(k, :) = rem(x, 2);
x = floor(x / 2);
end
  1 Comment
Quoc Khang Doan
Quoc Khang Doan on 26 Mar 2021
Edited: Quoc Khang Doan on 26 Mar 2021
What i want to achieve is convert every element in x, for example:
>> x = 0:5;
x = 0 1 2 3 4 5
into binary and store it into a matrix z like so:
>> mybinplot(5)
z =
0 0 0 0 1 1
0 0 1 1 0 0
0 1 0 1 0 1
thank you in advance

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!