How to make the cleaner smoother loop for the following example?
Show older comments
d21a = DIC(d.station == 21); u = unique(d.depth(d.station == 21)); n = histc(d.depth(d.station == 21),u); uu = u(n>1);
for i = 1:size(uu,1) rv = d.depth(d.station == 21) == uu(i); me = nanmean(d21a(rv)); d21a(rv) = me; end
d21b = d.depth(d.station == 21); d21(:,1) = d21b; d21(:,2) = d21a; d21 = sortrows(d21,1);
d.variables all = 444x1
I want to be able to specify how many stations (21:28) and then create variables related to the station within a loop. For example, instead of writing d21a, I would like something sort of like ['d', num2str(st),'a'] = blah blah. So far I haven't been able to crack it.
as at the moment, I am copying this code 8 times, one for each station (21:28), for four variables. So in total, 32 copies of this code, and it's too long.
I have already looked at the 'eval' function and I can't get it to work via converting a string to a variable....I think it's impossible...
thanks in advance, Michael
2 Comments
Use a cell array (assuming that you can't just use a standard array - that would depend on exactly what DIC( d.station == 21 ) returns ). One variable is better than 8 and is accessible via indexing rather than convoluted use of eval every time you wish to do something with a specific station.
Don't create (or name) new variables like that. You should consider using a non-scalar structure instead, which lets you define the structure using indices like this:
d(k).variables = [...];
d(k).depth = ...
d(k).station = ...
for any k, where the structure is indexed just like any MATLAB array and it can be a vector or matrix...
Accepted Answer
More Answers (0)
Categories
Find more on Variables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!