Find and replace value in a table

3 views (last 30 days)
Celina Brinkmann
Celina Brinkmann on 9 Oct 2021
Commented: Star Strider on 10 Oct 2021
Hi,
I am working with the table 'Samples' and I would like to find and replace values of the column 'Location'.
I would like to find the value 'Germany' and replace it with 'GER', find 'Australia' and replace it with 'AUS' and find 'Canada' and replace it with 'CAN'. How can I find these values and replace them?
I am new with matlab and would really appreciate any help!

Answers (1)

Star Strider
Star Strider on 9 Oct 2021
Try something like this —
Country = {'Australia';'Germany';'Canada';'United Kingdom';'France'};
Location = Country(randi(numel(Country),10,1));
Something = randn(10,1);
Samples = table(Location, Something)
Samples = 10×2 table
Location Something __________________ _________ {'Germany' } -0.64263 {'Australia' } 0.050271 {'Australia' } -0.02538 {'Canada' } -1.4615 {'United Kingdom'} -0.84455 {'Germany' } -0.54954 {'Australia' } 0.23321 {'France' } -0.052465 {'Australia' } 1.3437 {'Canada' } 0.33439
Abbrev = {'AUS'; 'GER'; 'CAN'};
for k = 1:numel(Abbrev)
Samples.Location(strcmp(Samples.Location,Country{k})) = Abbrev(k);
end
Samples
Samples = 10×2 table
Location Something __________________ _________ {'GER' } -0.64263 {'AUS' } 0.050271 {'AUS' } -0.02538 {'CAN' } -1.4615 {'United Kingdom'} -0.84455 {'GER' } -0.54954 {'AUS' } 0.23321 {'France' } -0.052465 {'AUS' } 1.3437 {'CAN' } 0.33439
The ‘Abbrev’ vector can of course be expanded to include abbreviations for the other ‘Country’ elements as well, if desired.
.
  2 Comments
Star Strider
Star Strider on 10 Oct 2021
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by