Filter löschen
Filter löschen

Save elements of an array in a byte variable.

19 Ansichten (letzte 30 Tage)
benl23
benl23 am 7 Okt. 2019
Bearbeitet: Eric Prandovsky am 3 Nov. 2023
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.
  2 Kommentare
David Hill
David Hill am 7 Okt. 2019
I'm not sure what your matrix looks like. Is it a logical matrix 4x8? (what is mat(32,5)? Do you want the bytes in decimal form? What format do you want you output array?
Stephen23
Stephen23 am 8 Okt. 2019
Bearbeitet: Stephen23 am 8 Okt. 2019
benl23 's "Answer" moved here and formatted properly:
I'm sorry for the lack of information.
My basic problem is that I can't create bytes from the elements of an array.
Let's say we have a logical array of 16 elements. I will then modify the solution for my specific case.
A=[0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0 ]
logA=logical(A);
How from this array can I create two uint8 in a way that:
var1=0b00100000;
var2=0b00001100;

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Johannes Fischer
Johannes Fischer am 8 Okt. 2019
% 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)])';
  1 Kommentar
Eric Prandovsky
Eric Prandovsky am 3 Nov. 2023
Bearbeitet: Eric Prandovsky am 3 Nov. 2023
I've used typecast(X,type) before, but it doesn't accept logical data for some reason. This is a good workaround.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu MATLAB Support Package for Arduino Hardware finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by