MATLAB: Save elements of an array in a byte variable.

arduinobyte

Hi to every one!
I've got a problem with an easy programming excercise.
I've got a logical matrix composed by logical elements ( mat(32,5) ). I need for each row to save the first 8 elements af the array in 1 byte variable, elements from 9 to 16 in a second byte and so on..
So that the end I will have 4 byte variables for each row to sent to arduino.
How can I do that? thank you all.

Best Answer

% random array of 8 rows with 4 bytes each
bin = logical(round(rand(8, 32)));
% how many bytes are there in total
NoBytes = size(bin, 2)/8*size(bin, 1);
% reshape the matrix into an array, where each row repsresents one byte
bArray = reshape(bin', [8, NoBytes])';
% now convert it into a cell array, where each cell contains a matrix of 8
% elements
bCell = num2cell(bArray, 2);
% now we take a detour over string represenation of the values to create a
% byte variable in each cell entry
bytes = cellfun(@(x) uint8(bin2dec(num2str(x))), bCell);
% reshape back into the original shape
bytes = reshape(bytes, [size(bin, 2)/8, size(bin, 1)])';