Info

This question is closed. Reopen it to edit or answer.

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

1 view (last 30 days)
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

Answers (1)

Ameer Hamza
Ameer Hamza on 6 Jun 2020
Edited: Ameer Hamza on 6 Jun 2020
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

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!