Need help writing script using "if" "then" type arguments and loops to pull specific data from long data file
1 view (last 30 days)
Show older comments
I have a data file that contains 3 columns (A, B, C). Column A is an indexing file and Columns B and C contain data. I would like to generate a new, two column matrix that contains only specific data from Columns B and C that are dependent on events in Column A. I need matlab to find the value in Column B when Column A switches from 3 to 2 (the value in Column B remains constant during switching) and find the value in Column B when Column A switches from 2 to 3 (the value in Column C remains constant during switching). The desired output file for the data provided here is:
0.00081966 / 0.00057264
0.0014508 / 0.00087722
0.0019136 / 0.0011055
0.0022935 / 0.0012946
(the text shows "/" between columns to be clear)
I believe I can do this with an "if" "then" type scenario (ie if the second row in column A minus the first row in Column A = 1, then the new value should be the value in Column B, etc), but cannot figure out how to loop it through the entire column A. Any help is really appreciated! Thank you!
0 Comments
Accepted Answer
Star Strider
on 10 Jul 2015
This seems to work:
fidi = fopen('Kimberly S data3.txt', 'rt');
C = textscan(fidi, '%f%f%f', 'Delimiter','\t', 'CollectOutput',1, 'EndOfLine','\r\n', 'HeaderLines',1);
fclose(fidi);
D = cell2mat(C);
trn = [0; diff(D(:,1))];
trn23 = find(trn == 1);
trn32 = find(trn == -1);
for k1 = 1:length(trn23)
Result(k1,:) = [D(trn32(k1),2) D(trn23(k1),3)];
end
2 Comments
More Answers (1)
Roger Stafford
on 10 Jul 2015
Rather than using 'if' constructs I think it would be better to use logical indexing, or perhaps in this case the 'find' function. Here is an example. Call your three-columned matrix, 'M'.
f = find(diff(M(:,1)) ~= 0); % Find where 1st column changes
R = M(f,2:3); % Save only the corresponding 2nd and 3rd columns in R
See Also
Categories
Find more on Loops and Conditional Statements 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!