How can I repeat same process for different matrices?

1 view (last 30 days)
I have 8 timeseries from different tide gauges. The first column of these matrices is deciyear, the second column is sea level.
I want to define -99999 as NaN in the second columns (i.e. the sea level) for each matrices. I know how to do this in a single matrix:
e.g. for the variable ' Boston ':
Name Size Bytes Class Attributes
Boston 1176x4 37632 double
Sea_Level_of_Boston = Boston(:,2);
Sea_Level_of_Boston(Sea_Level_of_Boston == -99999)= NaN;
Boston(:,2) = Sea_Level_of_Boston;
However, I want to repeat this for all the timeseries (e.g. Bridgeport, Eastport). I am curious if there is a easy way for that?
PS: all the matrices have 4 columns but they have different length, i.e. the time span various.
I have done combining the matrices, but I really want to seperate them afterwards for plotting and analysing.
  2 Comments
Stephen23
Stephen23 on 21 Sep 2019
This line will throw an error:
Sea_Level_of_Boston(Sea_Level_of_Boston = -99999)= NaN;
% ^ this is NOT an equivalence operator!
The equivalence operator in MATLAB is ==, aka eq.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 21 Sep 2019
Edited: Stephen23 on 21 Sep 2019
Of course there is an easy way: just use Indexing! Indexing is simple and very efficient:
C = {boston,paris,beijing,...};
for k = 1:numel(C)
M = C{k};
X = M(:,2)==-99999;
M(X,2) = NaN;
C{k} = M;
end
Or simply avoid creating M altogether:
C = {boston,paris,beijing,...};
for k = 1:numel(C)
X = C{k}(:,2)==-99999;
C{k}(X,2) = NaN;
end
"but I really want to seperate them afterwards for plotting and analysing."
Also trivially easy using exactly the same indexing.
Note that putting meta-data into variable names, e.g. boston and Sea_Level_of_Boston, is a bad idea, because trying to access meta-data in variable names is one way that beginners force themselves into writing slow, complex, obfuscated, inefficient, buggy code that is difficult to debug.
Meta-data is data, and data should be stored in variables, not in variable names.
  4 Comments
Tongyao Pu
Tongyao Pu on 21 Sep 2019
Ah I see. I had some misunderstanding. Finally the new values are saved in C. I shouldn't expect them in the previous variables. Thank you very much!
Stephen23
Stephen23 on 21 Sep 2019
"I shouldn't expect them in the previous variables."
Correct.
And in future, when designing your data, keep in mind that meta-data (e.g. city names) belongs in varables and not in variable names. Then your code will be simpler, more robust, and much more efficient.

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!