Inverse lookup table - matlab

This is a follow up question from a previous SO question. Now I have a bit which I have spread it into 8 bits. I have use Amro's solution to spread the bit to 8 bits. Now I want an inverse way to convert the 8bits back to the single bit.
I have only managed to implement the inverse using for loop which take alot of time in the application.
Is there a faster way of doing it?

Since you are using the solution I suggested last time, lets say you have a matrix N-by-8 of these 'bits' where each row represent one 8-bit binary number. To convert to decimal in a vectorized way, its as simple as:
» M = randi([0 1], [5 8]) %# 5 random 8-bit numbers
M =
1 0 1 0 1 0 1 1
0 1 1 0 1 1 1 0
1 1 0 1 1 0 1 1
1 0 0 0 0 1 1 0
1 0 0 1 0 1 1 0
» d = bin2dec( num2str(M) )
d =
171
110
219
134
150
An alternative solution:
d = sum( bsxfun(#times, M, power(2,7:-1:0)), 2)

Related

Combinations of zeros and ones of vector size n [duplicate]

I have an algorith that the number of possibles combinations of 0 and 1, can reach the number 2^39. Let's say i have n=2 situations, or n1=2^2=4 combinations of 0 and 1: 00,01,10,11.From that i can create an array a=zeros(n,n1) and fill the columns with the possible combinations? That means first column has 00,second 01,third 10,last 11.I want this to be dynamic that means that n can be 1,2,3...,39, show the array will be a=zeros(n,2^n).Thanks for any response!
Just for general understanding: why do you think you need an array of all combinations of all integers from 0 to 2³⁹? That array would consume 39×2³⁹/1000⁴ ≈ 21TB of RAM...last time I checked, only the world's most advanced supercomputers have such resources, and most people working with those machines consider generating arrays like this quite wasteful...
Anyway, for completeness, for any N, this is the simplest solution:
P = dec2bin(0:(2^N)-1)-'0'
But, a little piece of advice: dec2bin outputs character arrays. If you want numerical arrays, you can subtract the character '0', however, that gives you an array of doubles according to the rules of MATLAB:
>> P = dec2bin(0:(2^3)-1)-'0';
>> whos P
Name Size Bytes Class Attributes
P 8x3 192 double
If you want to minimize your memory consumption, generate a logical array instead:
>> P = dec2bin(0:(2^3)-1)=='1';
>> whos P
Name Size Bytes Class Attributes
P 8x3 24 logical
If you want to also speed up the execution, use the standard algorithm directly:
%// if you like cryptic one-liners
B1 = rem(floor((0:pow2(N)-1).' * pow2(1-N:0)), 2) == 1;
%// If you like readability
B = false(N,pow2(N));
V = 0:pow2(N)-1;
for ii = 1:N
B(ii,:) = rem(V,2)==1;
V = (V-B(ii,:))/2;
end
That last one (the loop) is fastest of all solutions for any N (at least on R2010b and R2013a), and it has the smallest peak memory (only 1/Nth of the cryptic one-liner).
So I'd go for that one :)
But, that's just me.
Using ndgrid with a comma-separated list as output (see also here):
[c{1:N}] = ndgrid(logical([0 1]));
c = cat(N+1,c{N:-1:1});
c = reshape(c,[],N);
Example: N=4 gives
c =
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1

Is there a fast way to count occurrences of items in a matrix and save them in another matrix without using loops?

I have a time-series matrix X whose first column contains user ID and second column contains the item ID they used at different times:
X=[1 4
2 1
4 2
2 3
3 4
1 1
4 2
5 3
2 1
4 2
5 4];
I want to find out which user used which item how many times, and save it in a matrix Y. The rows of Y represent users in ascending order of ID, and the columns represent items in ascending order of ID:
Y=[1 0 0 1
2 0 1 0
0 0 0 1
0 3 0 0
0 0 1 1]
The code I use to find matrix Y uses 2 for loops which is unwieldy for my large data:
no_of_users = size(unique(X(:,1)),1);
no_of_items = size(unique(X(:,2)),1);
users=unique(X(:,1));
Y=zeros(no_of_users,no_of_items);
for a=1:size(A,1)
for b=1:no_of_users
if X(a,1)==users(b,1)
Y(b,X(a,2)) = Y(b,X(a,2)) + 1;
end
end
end
Is there a more time efficient way to do it?
sparse creates a sparse matrix from row/column indices, conveniently accumulating the number of occurrences if you give a scalar value of 1. Just convert to a full matrix.
Y = full(sparse(X(:,1), X(:,2), 1))
Y =
1 0 0 1
2 0 1 0
0 0 0 1
0 3 0 0
0 0 1 1
But it's probably quicker to just use accumarray as suggested in the comments:
>> Y2 = accumarray(X, 1)
Y2 =
1 0 0 1
2 0 1 0
0 0 0 1
0 3 0 0
0 0 1 1
(In Octave, sparse seems to take about 50% longer than accumarray.)

Generate truth table in MatLab

I want to create a truth table in MatLab with i columns and i2 rows. For example, if i=2, then
T =
[0 0]
[1 0]
[0 1]
[1 1]
Code to do this has already been created here
This is part of a larger project, which requires i large. Efficiency is a concern. Is there more efficient code to create a truth table? Does MatLab have a built in function to do this?
Edit: Sorry about the formatting!
Something like this?
n=2;
d=[0:2^n-1].';
T=dec2bin(d,n)
T =
00
01
10
11
dec2bin will give you a character array, which you can convert to logical, if needed. There's also de2bi that gives you a numeric array directly, but you need a newer version of Matlab and the ordering of the bits is reversed.
Here's Luis Mendo's speedup, which replicates dec2bin (n and d are as above):
T=rem(floor(d*pow2(1-n:0)),2);
ndgrid is very much your friend here:
function t = truthTable(n)
dims = repmat({[false, true]}, 1, n);
[grids{1:n}] = ndgrid(dims{:});
grids = cellfun(#(g)g(:), grids, 'UniformOutput',false);
t = [grids{:}];
First you need to create grids for the number of dimensions in your truth table. Once you have those you can columnize them to get the column vectors you need and you can horizontally concatenate those column vectors to get your truth table.
I imagine the performance of this will be quite competitive.
>> truthTable(2)
ans =
0 0
1 0
0 1
1 1
>> truthTable(4)
ans =
0 0 0 0
1 0 0 0
0 1 0 0
1 1 0 0
0 0 1 0
1 0 1 0
0 1 1 0
1 1 1 0
0 0 0 1
1 0 0 1
0 1 0 1
1 1 0 1
0 0 1 1
1 0 1 1
0 1 1 1
1 1 1 1
>>
>> timeit(#() truthTable(20))
ans =
0.030922626777
EDIT: Use reshape instead of column dereferencing for further performance improvement
function t = truthTable(n)
dims = repmat({[false, true]}, 1, n);
[grids{1:n}] = ndgrid(dims{:});
grids = cellfun(#(g) reshape(g,[],1), grids, 'UniformOutput',false);
t = [grids{:}];
>> timeit(#() truthTable(20))
ans =
0.016237298777
I know this question has been dead a while, but I was wondering the same thing and found a solution I like a lot. Thought I'd share it here:
fullfact(ones(1, i) + 1) - 1

Matlab matrix-multiplication and transpose precision

The next script should print out a 7x7 all-ones matrix, because the equation is satisfied.
A = rand(5,7);
B = rand(5,7);
C = (A' * B)';
D = B' * A;
C == D
Instead of this kind of answer:
ans =
1 1 1 1 0 1 1
1 1 1 1 0 1 0
1 1 1 1 1 1 1
1 1 1 1 0 0 0
1 0 1 1 1 1 1
0 0 1 1 1 1 1
0 1 1 0 1 1 1
I think this is a floating-point precision problem, because with format long the numbers differ in C and D.
What do I do wrong?
Where does it go wrong?
How can I avoid it?
You don't do anything wrong - the computer has finite precision, and your calculation reveals it - just like 1e6 + 0.1 - 1e6 (try it in Matlab). One way to avoid it is to use some library for arbitrary precision - but it won't 'solve' it, just push the problem towards smaller and smaller numbers.
See these links for some more info:
http://floating-point-gui.de/errors/comparison/
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
By the way, format long has nothing to do with the actual precision, it just sets the way the numbers are formatted for displaying.

Fastest way to copy values between two matrix

I am looking for a fastest way to copy some special value of a matrix to other matrix. Assume that I have matrix A such as
A =[4 1 5 4 4
-2 -1 1 2 2
3 -1 1 7 3
5 3 -1 1 -2
6 4 4 -1 1]
My aim is that copy element that have value 1 and -1 to matrix B. The expected matrix B such as
B =[ 0 1 0 0 0
0 -1 1 0 0
0 -1 1 0 0
0 0 -1 1 0
0 0 0 -1 1]
I performed two way to create matrix B. However, I think that my way is still not fastest way if size of matrix A becomes larger. I know that the forum has many expert matlab guy. Could you suggest to me another way?
This is my code
%%First way:
tic;B=((A==1)|(A==-1)).*A;toc
Elapsed time is 0.000026 seconds.
%%Second way:
tic;idx1=find(A==1);idx2=find(A==-1);B=zeros(size(A));B(idx1)=1; B(idx2)=-1;toc;B
Elapsed time is 0.000034 seconds.
here's somthing on par with #thewaywewalk
B=A.*reshape(abs(A(:))==1,size(A));
This is how I test these:
A=randi(10,1000,1000)-7;
B1=#() ((A==1)|(A==-1)).*A;
B2=#() (abs(A) == 1).*A;
B3=#() A.*reshape(abs(A(:))==1,size(A));
timeit(B1)
ans =
0.0136
timeit(B2)
ans =
0.0080
timeit(B3)
ans =
0.0079
These will change from run to run, but the methods are on par...
here's the same test on a range of matrix sizes:
The only thing which comes to my mind, which could be faster:
B = (abs(A) == 1).*A;