MATLAB Answers

How to get a column from a text file based on some conditions

5 views (last 30 days)
Gautam Kollabathula
Gautam Kollabathula on 6 Jun 2020 at 5:36
Edited: Ameer Hamza on 6 Jun 2020 at 7:58
Hello, the text file i have has below data
Node C: -62
Node B: -71
Node A: -72
Node C: -62
Node C: -62
Node C: -61
Node B: -69
Node A: -56
Node A: -72
Node A: -57
Node A: -56
Node C: -76
I want to read this text file and create three array's based on the node type i.e. A,B,C.
i.e. Array1 has to include the value in column3 whose column 2 is A
Array2 has to include all values from column3 whose column2 is B.
Array3 has to include all values from column3 whose column3 is C.
How do i do it? I am a novice in Matlab and am struggling to understand how to segregate this.
Thanks for your help

  0 Comments

Sign in to comment.

Answers (1)

Ameer Hamza
Ameer Hamza on 6 Jun 2020 at 7:58
Edited: Ameer Hamza on 6 Jun 2020 at 7:58
Try this
data = fileread('test.txt');
data = textscan(data, 'Node %1s: %f');
labels = [data{1}{:}]-64;
vals = data{2};
Array = accumarray(labels.', vals, [], @(x) {x});
Array is a cell array with 3 elements
Array{1} % values for node A
Array{2} % values for node B
Array{3} % values for node C

  0 Comments

Sign in to comment.