Filter löschen
Filter löschen

Joining every eight columns in a matrix

2 Ansichten (letzte 30 Tage)
Nick DeMarchis
Nick DeMarchis am 22 Mai 2019
Kommentiert: Rik am 22 Mai 2019
Hi there! Right now I have a (large by 46) double Matrix. An example is shown below:
[1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8; ...]
I'd like to update it so that it is:
['12345678' '12345678'; ...]
I know that it should be something with character joining but I'm just not quite sure of what the exact steps are.
Thanks for your help!

Akzeptierte Antwort

Rik
Rik am 22 Mai 2019
Bearbeitet: Rik am 22 Mai 2019
Although it might visually be joining characters, that is not necessarily what you need. The code below should be one of the faster methods, although it breaks when your elements are larger than 9 or non-integer. The nice thing about this system is that you can replace fun with any function (or handle to a function) so you can make sure it does the conversion in a way you want.
bigData=[1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8; ...
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8; ...
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8];
a=mat2cell(bigData, ones(size(bigData,1),1), [8 8]);
fun=@(x) polyval(x,10);
b=cellfun(fun,a);
If you do want to convert to characters, do the join and convert back to double:
fun=@(x) str2double(cell2mat(cellfun(@num2str,num2cell(x),'uni',0)));
Although that function will also break for non-integer values.
  2 Kommentare
Nick DeMarchis
Nick DeMarchis am 22 Mai 2019
I've just realized that my array is actually 46 characters wide and, therefore, double spaced as seen above. I can't figure out where this is affecting the code, but it gives me an error.
How does this new information affect the code?
Rik
Rik am 22 Mai 2019
In that case it appears your data is not actually a double array, but a char array. That makes it a bit easier, as we can just remove the spaces and optionally convert the result to a double array.
bigData=['1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8'; ...
'1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8'; ...
'1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8'];
%remove all spaces
a1=strrep(bigdata,' ','');
%divide lines in two blocks of 8 (using a cell array)
a2=mat2cell(a, ones(size(a,1),1), [8 8]);
%convert char to double
b=cellfun(@str2double,a2);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by