Emma
Emma

Reputation: 618

splitting a string in matlab

In order to make this question easier to describe I have provided the following example code, which is similar to the actual data I am working with:

clear all
AirT = {rand(32,1),rand(32,1),rand(32,1),rand(32,1)};
SolRad = {rand(32,1),rand(32,1),rand(32,1),rand(32,1)};
Rain = {rand(32,1),rand(32,1),rand(32,1),rand(32,1)};
Location = {'England','Wales','Scotland','Ireland'};
points = {'old','old','old','new'};
CorrVariables = {'AirT','SolRad','Rain'};
for i = 1:length(Location);
    Data = @(location) struct('Location',location,CorrVariables{1},AirT{i},...
        CorrVariables{2},SolRad{i},CorrVariables{3},Rain{i});
    D(i) = Data(Location{i});
end
FieldName = {D.Location};
R = corrcoef([D.AirT],'rows','pairwise');
R_Value = [Location(nchoosek(1:size(R,1),2)) num2cell(nonzeros(tril(R,-1)))];
q = points(nchoosek(1:size(R,1),2));
    %to calculate the combination of these points we need to convert the
    %cell into a matrix.
Re = [R_Value q];

From this example I would like to create another cell array in column 5 of Re which is dependant on the strings in columns 4 and 5. So, if columns 4 and 5 in Re are equal, such as 'old''old' then column 6 should show 'old'. However, if the cells differ e.g. 'old' 'new' then I would like the new cell array (i.e. column 6 in Re) to state 'old/new'.

How would this be possible?

Upvotes: 0

Views: 1283

Answers (1)

MattLab
MattLab

Reputation: 303

From your description I think the clearest approach is to use a combination of string concatenation and regular expressions.

First combine columns 4 and 5 into a new column:

newColumn = strcat(Re(:,4), '/', Re(:,5));

Now look for the repeated pattern and replace with the first token matched:

newColumn = regexprep(newColumn, '(\w+)/\1', '$1');

Combine into existing cell matrix:

Re = [Re, newColumn];

Upvotes: 2

Related Questions