Zed Kay
Zed Kay

Reputation: 133

Changing the value of elements in a table, depending on a specific string for MATLAB

Suppose I have a MATLAB table of the following type:

Node_Number Generation_Type Total_power(MW)

1           Wind             600 
1           Solar            452
1           Tidal            123
2           Wind             200
2           Tidal            159

What I want to do is to produce a table with exactly same dimensions, with the only difference being the value of the data of the Total_Power column that corresponds to the Wind generation type being multiplied with 0.5. Hence the result that I would get would be:

Node_Number Generation_Type Total_power(MW)

1           Wind             300 
1           Solar            452
1           Tidal            123
2           Wind             100
2           Tidal            159

What I believe that would do the trick is some code which would scan all the rows that have the string 'Wind', and then after locating the rows which have this string, to multiply the 3rd column of this row with 0.5. A for loop seems like a viable solution, though I am not sure how to implement this. Any help would be greatly appreciated.

Upvotes: 0

Views: 73

Answers (1)

Hunter Jiang
Hunter Jiang

Reputation: 1300

Just find the index of rows with the category Wind, and then you could have access to them by calling T(index,:).

clc; clear;
T=readtable('data.txt');
rows = find(ismember(T.Generation_Type,'Wind'));
T(rows,:).Total_power_MW_=T(rows,:).Total_power_MW_*0.5

Output:

Node_Number    Generation_Type    Total_power_MW_
___________    _______________    _______________

1              'Wind'             300            
1              'Solar'            452            
1              'Tidal'            123            
2              'Wind'             100            
2              'Tidal'            159   

Upvotes: 1

Related Questions