Split information from the same cell into diferent cells

Hello, I have an excel file and it has 2 columns and a lot of lines. The first column has numbers and the second column has words like this "House_red". I used this to extract the second column
[~,houses] = xlsread('houses.xlsx', 'B:B');
And right now I have all my information separated numbers from strings, but in the strings I wanted to split house from red where house will be in the first column and red in the second column. Is there a way to do split strings from the same line into different lines/columns?

 Risposta accettata

Try this:
houses = {'House_red'; 'House_blue'; 'House_green'};
s = regexp(houses, '_', 'split');
H = cellfun(@(x)x(:,1), s);
C = cellfun(@(x)x(:,2), s);
HC = [H, C]
HC =
3×2 cell array
{'House'} {'red' }
{'House'} {'blue' }
{'House'} {'green'}

8 Commenti

Hi, I forgot to say, but I don't have only houses, I have apartments, stores, garage, and a lot of other stuff but is known that before _ is the type of the place and after the _ is the color. Thank you.
No problem. The type of building does not matter. My code will work for all of them:
houses = {'House_red'; 'Store_blue'; 'Garage_green'; 'Apartment_fuchsia'};
s = regexp(houses, '_', 'split');
H = cellfun(@(x)x(:,1), s);
C = cellfun(@(x)x(:,2), s);
HC = [H, C]
HC =
4×2 cell array
{'House' } {'red' }
{'Store' } {'blue' }
{'Garage' } {'green' }
{'Apartment'} {'fuchsia'}
yes, it worked. Thank you so much, if we had a string like this 'House_x_red' in the same file how would you approach it?
My pleasure.
It would have been helpful to have known this before. I would use the same code, then assign the 'x' to either the building or color, however you want to do it. I cannot find a way for regexp to split one underscore and leave the other unchanged.
s = regexp(houses, '_', 'split', 'once');
stops splitting after the first underscore.
@Walter — Thank you.
I didn’t see that in the documentation when I looked a few minutes ago.
How does @(x)x(:,1) works?
@Muna Awajan — When used in the cellfun function, it extracts the first column of cell array ‘s’ and returns it as a separate cell array (here, ‘H’).

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by