Merge elements of a row into a single element array

Hi,
I want to merge each row of CHAR type matrix
BB=[C I M G 2 8 3 0; C I M G 2 8 3 2; C I M G 2 8 3 3; C I M G 2 8 3 4]
as
BBB=[CIMG2830; CIMG2832; CIMG2833; CIMG2834]
or in other words I want to merge each row into one single element, not necessarily all elements are numbers.
Any ideas?

 Risposta accettata

BB=['C' 'I' 'M' 'G' '2' '8' '3' '0'; 'C' 'I' 'M' 'G' '2' '8' '3' '2'; 'C' 'I' 'M' 'G' '2' '8' '3' '3'; 'C' 'I' 'M' 'G' '2' '8' '3' '4']
is already completely equivalent to
BBB = ['CIMG2830'; 'CIMG2832'; 'CIMG2833'; 'CIMG2834']
Are you sure you are starting with a char matrix? And not, perhaps, a cell array whose elements are each single char ? If what you have is
BB={'C' 'I' 'M' 'G' '2' '8' '3' '0'; 'C' 'I' 'M' 'G' '2' '8' '3' '2'; 'C' 'I' 'M' 'G' '2' '8' '3' '3'; 'C' 'I' 'M' 'G' '2' '8' '3' '4'}
then
BBB = reshape( horzcat(BB{:}), size(BB,1), [])

3 Commenti

MATLAB says they are type CHAR. Padding them manually is trivial, I'm looking for a generic way that I can apply to any random CHAR array that another time I shouldn't have to write them manually but with the help of a piece of code.
How I get this CHAR array is as follows.
I get directory list of a specific place in PC via
AA=dir(folder);
I extract name list from struct AA
aa={AA.name};
Now I have a CELL array of
aa=
{'CIMG2830' 'CIMG2832' 'CIMG2833' 'CIMG2834' 'DSC_0006' 'DSC_0007' 'DSC_0008' 'DSC_0010' 'SAM_0002' 'SAM_0003' 'SAM_0004' 'SAM_0005' 'SS856007' 'SS856008' 'SS856009'}
When I use cell2mat(aa') and so I have a CHAR type 15x8 array of
[C I M G 2 8 3 0;
C I M G 2 8 3 2;
C I M G 2 8 3 3;
C I M G 2 8 3 4;
.....
S S 8 5 6 0 0 9;]
Since I need a 15x1 array of
[CIMG2830;
CIMG2832;
CIMG2833;
CIMG2834;
.....
SS856009;]
where each entry is a folder name at somewhere in PC.
So I'm looking for a way to get proper names of folders.
Do not use cell2mat() for that purpose. Instead, use
char(aa)
as that will convert the cell array of strings into a row-based array of char.
However, you would seldom need that. You would typically instead use something like,
filename = aa{k};
fullname = fullfile(folder, filename);
That worked great for me. Thank you for pointing a torch on this.

Accedi per commentare.

Più risposte (0)

Categorie

Community Treasure Hunt

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

Start Hunting!

Translated by