Typecasting higher dimension matrices
30 次查看(过去 30 天)
显示 更早的评论
I recently found (to my chagrin) that the typecast function only works on scalars and 1D matrices (i.e. arrays).
Does anyone know of a way to typecast matrices with 2, 3, 4, or more dimensions (other than simply indexing out and typecasting all the elements or 1st dimension arrays into a new variable?
2 个评论
Florin Neacsu
2011-9-21
Hello,
What do you mean?
A=[2,2;1,3];
B=single(A);
seems to work.
Regards,
Florin
采纳的回答
Walter Roberson
2011-9-21
Suppose you had a 3 x 12 uint8 matrix, and wanted to typecast it to uint32: what would you want that to mean? What shape would you expect the result to be? There is the right amount of data there to make it in to 9 uint32 but 3 x 3 would surely be the wrong shape for the output, considering that the 4th byte of the first uint32 would have to be taken from the top row of the second column of the input array.
About the only way that would make sense to me to more or less preserve the dimensions would be if, when a type was being typecast to another type, the first dimension of the output would be adjusted so as the occupy the same number of bytes per column as the original first dimension did (getting bigger if the new type used less room, getting smaller if the new type occupied more room), with it being an error if the first column could not be converted to an integral number of items in the new type.
If that is the rule you would use, it would not be difficult to implement it. Keep in mind that reshape() and (:) do not move data around, just put a new header on it, so the operations would be fast:
function NewArray = typecastarray(TheArray, NewType)
curshape = num2cell(size(TheArray));
NewArray = reshape( typecast(TheArray(:),NewType), [], curshape{2:end});
end
1 个评论
VINAYAK KARANDIKAR
2019-1-9
This does not work for audio data. For example an array(2 channel) audio file of char type, when type-casted into a uint8 array(becasue sound and wavplay command do not accept data types of char type), and if the audio is played, we hear garbage, that's why!!!
更多回答(1 个)
Carl Witthoft
2020-3-30
If you know a little bit about your 2D array in advance, then try this - seemed to work for me
Here I know my columns are 4*N bytes long, and that I want to typecast column-wise
arrsize = size(arrdat);
f32 = zeros(arrsize(1)/4, arrsize(2) );
for jrow = 1:4:size(arrdat,1),
count4 = jrow:jrow+3;
rowquad = arrdat(count4,:);
f32((1+(jrow-1)/4),:) = double(typecast(rowquad(:), 'single'));
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String Parsing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!