If I have a number in one table column, how do I add a new column where the numbers in the second column depend on on the first column. For example, if the first column = 1, new column = 0, if first column = 4, new column = 0.2, if 9, new column = 0.5 etc. I don't want to replace the first column but want to add a second column that is based on the first. I feel I should be using if statements but am new to matlab and I just don't seem to be understanding how to use these yet.
I have attached a table to show how it should look. (The actual table has about 500,000 rows).
Much appreciated, Wendy

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 18 Mai 2018

0 Stimmen

num = xlsread('Crop factor.xls');
input_table = [1, 4, 9];
replacement_table = [0, 0.2, 0.5];
new_column = nan(size(num));
[tf, whichcase] = ismember(num, input_table);
new_column(tf) = replacement_table(whichcase(tf));
This will leave nan for any column that was not matched.

4 Kommentare

Wendy Cameron
Wendy Cameron am 18 Mai 2018
Yes thanks that works and then I suppose I can add the new column back into the original table. I hadn't come across whichcase before and assumed I'd need if statements.
Thanks, Wendy
Wendy Cameron
Wendy Cameron am 18 Mai 2018
Actually I've just thought of another way. If you created a repeat of the Month column so it could be written over you could do CropFactor.Month(Cropfactor.Month==1)=0; Cropfactor.Month(Cropfactor.Month==4)=0.2; etc to replace the month value with the required value.
Wendy Cameron
Wendy Cameron am 18 Mai 2018
...which wasn't what I originally asked for but the great thing about the forums is the interaction and ideas and learning. Thanks!!
Walter Roberson
Walter Roberson am 18 Mai 2018
whichcase is just an arbitrary variable name; the key is that it is the second output of ismember()
Using logical indexing is fine for a small number of cases, but it gets out of hand quickly as you add more cases. With the ismember() version, you can expand to as many replacements as you need just by adding to input_table and replacement_table.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by