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?

 採用された回答

Star Strider
Star Strider 2018 年 6 月 21 日

1 投票

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 件のコメント

Marta Ramos
Marta Ramos 2018 年 6 月 21 日
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.
Star Strider
Star Strider 2018 年 6 月 21 日
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'}
Marta Ramos
Marta Ramos 2018 年 6 月 21 日
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?
Star Strider
Star Strider 2018 年 6 月 21 日
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.
Walter Roberson
Walter Roberson 2018 年 6 月 21 日
s = regexp(houses, '_', 'split', 'once');
stops splitting after the first underscore.
Star Strider
Star Strider 2018 年 6 月 21 日
@Walter — Thank you.
I didn’t see that in the documentation when I looked a few minutes ago.
Muna Awajan
Muna Awajan 2022 年 5 月 2 日
How does @(x)x(:,1) works?
Star Strider
Star Strider 2022 年 5 月 2 日
@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’).

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by