# Read values from .txt file to vectors in Matlab

I have data in a text file, which contains varying amount of columns at each row in the text file. The data I have is at following format:

2

21 2623

707 40 1

After there's three numbers in a row the data remains at the same structure until the end of file. I want to process the data so I have three vectors X, Y and Z, which contains the values from rows which have three numbers, so that:

X = 707

Y = 40

Z = 1

Thanks a lot!

Assuming the number of rows to ignore is not constant and you want to do this programmatically rather than using the import wizard, you'll first need to figure out how many rows there are to ignore.

One method to do this would be to use `fgetl`, which goes through a file line-by-line. Once you have the number of headers you can then read in the data with a function like `dlmread` or `textscan`.

For example:

`fID = fopen(myfilepath, 'r'); % Open data file for reading`

``` ncoldesired = 3; ii = 0; % Search for the first row of "good" data while ~feof(fID) % Loop will stop if it reaches the end of the file tline = fgetl(fID); temparray = str2num(tline); % Convert string to array of doubles, could also use regex if length(temparray) == ncoldesired % Found the first row of data nheaders = ii; fclose(fID); break end ii = ii + 1; end % Error Catching if exist('nheaders', 'var') == 0 && feof(fID) fclose(fID); error('End of file reached, no good data found'); end ```

```mydata = dlmread(myfilepath, ' ', nheaders, 0); % For some reason dlmread uses zero-based indexing unlike everything else in MATLAB ```

If you do not need to store the first three rows, you can use either `textscan` specifying the property `'headerlines' 3` or dlmrear specifying the property `'roffset'` 4.

Hope this helps.

You can use a combination of `cellfun` and `cell2mat`.

` rowContainsThreeElems = cellfun(@(x) size(x,2)==3, tline_c);`

``` ```

```% // Get those rows A= cell2mat(tline_c(rowContainsThreeElems==1)) A = 707 40 1 ```

```% // Data.txt % // -------------- % // 2 % // 21 2623 % // 707 40 1```

``` % // Read in the file and convert it to an array fid = fopen('data.txt','r'); tline = fgets(fid); tline_c = {}; n = 1; while ischar(tline) disp(tline) % // Convert the line to a numeric array but store it in a cell array tline_c{n} = str2num(tline); tline = fgets(fid); n=n+1; end fclose(fid); % // Get the lines that have three elements rowContainsThreeElems = cellfun(@(x) size(x,2)==3, tline_c); rowContainsThreeElems = 0 0 1 % // Get those rows A= cell2mat(tline_c(rowContainsThreeElems==1)); ans = 707 40 1 ```

```% // Add them to X,Y,Z X=A(:,1); Y=A(:,2); Z=A(:,3); ```

Category:matlab Views:0 Time:2018-09-13

## Related post

• How to read values from property file in a JavaBean (domain class)? 2011-01-19

I have a domain class and I want to read values from property file (autowiring messageSource wouldn't work here) so any ideas ? I am using spring,hibernate and here's a sample: package com.myapp.domain; import java.io.Serializable; import javax.persi

• Selenium: How to read values from any file (text, excel or csv)? 2011-06-01

Some of my project data needs to be changed every time i run the script. In order to have automated system i require to read values from any file and send its data as input to selenium script. --------------Solutions------------- If you are using Sel

• How to read values from properties file? 2012-02-13

I am using spring. i need to read values from properties file. This is internal properties file not the external properties file. properties file can be as below. some.properties ---file name. values are below. abc = abc def = dsd ghi = weds jil = sd

• Read Values from xml file 2010-03-08

I have a function TRANSLATE which reads value from the xml file based on a key. I wanna put "http://www.google.com?search=" in the xml file and read it based on the key(SEARCHER) I am confused in framing the link when it comes in Response.Write <%

• Read values from resx files? 2010-04-17

How to read strings from the MyResource.resx file from c#. I am not calling this from the asp.net page, rather i am calling from my bussiness logic. Assembly assembly = this.GetType().Assembly; ResourceManager resourceManager = new ResourceManager("M

• Failing to read values from a file 2010-12-02

The program below should read in a bunch of integers from a file and work out their average: #include "stdafx.h" #include <iostream> #include <string> #include <fstream> using namespace std; int main( int argc, char** argv ) { ifstr

• Reading doubles from .txt file into a List 2011-03-30

I'm trying to read doubles from a .txt file and put them all into a list. Here's my code so far -> (I have one method to ask for the file and get the data stream, and one to put the doubles into a list.) public InputFile () throws MyException { fi

• reading data from txt file in fortran 2012-01-11

I am writing a FORTRAN program that reads data from a text file and writing it to the console. the data file looks something like this 1234567890123456 123456.789 987654.321 673647.890 654356.890 6172876534567890 768909.098 234543.890 654321.908 9878

• How to read/write from .txt file in android 2014-05-15

I'm trying to import a list of words into an arraylist from a .txt file. Right now i'm placing my .txt file into the assets folder. So far i can do this using the following code try { AssetManager am = this.getAssets(); InputStream inputStream = am.o

• C#: Read data from txt file 2010-11-16

I have an .EDF (text) file. The file's contents are as follows: ConfigFile.Sample, Software v0.32, CP Version 0.32 [123_Float][2] [127_Number][0] [039_Code][70] I wnat to read these items and parse them like this: 123_Float - 2 127_Number - 0 039_Cod

• reading values from text file 2011-06-07

Please explain the compiler behaviour in the below code snippet. Consider the text file contains the following text TOBE and the corresponding byte values are 84, 79, 66, 69 for(int i=0;i<4;i++){ byte inByte=(byte) buffInputFile.read(); system.out

• action script 3 read values from XML file 2011-09-13

I have a problem while reading from XML file in action script 3. This is my XML-file: <config> <production> <app_id>123</app_id> <server_path>http://someLinktoAccess</server_path> <assets_server>http://someLi

• Solved: Change values from .txt file 2012-12-16

If one variable in file1.txt matches identical variable in file2.txt , change that variable from file1.txt to the "=" value from text2.txt, and save as corrected value(only)to file3.txt (keeping the variables in order from file1.txt) Example: file1.t

• Array values from .txt file in java 2016-02-01

I'm trying to get this code to print an array from a .txt file but the error: cannot find symbol for variable i pops up. I have no idea why final int SIZE2 = 15; int[] ages = new int[SIZE2]; Scanner finAges = new Scanner(new File("members.txt"))

• Reading valued from properties file at Runtime 2011-04-14

I want to get specific value based on request from the property file.how to do that? I have following spring configuration.i want to set the value for Exprops as per the request and get corresponding values from the properties file <bean id="Prop"

• Flex: create buttons dynamically and assign value from txt file 2011-07-17

I made a basic text editor that lets users insert predefined strings into the document with button clicks. What I need to do now is let the user define their own buttons and string values. For example I have a button that inserts "Hello" into the tex

• Read Value from Resource file using String 2011-10-04

I have an enum with some data on it, also I have a resource file with the same data of the enum but using different translation Ex. enum test { Sun =1, Mon = 2 } The resource file : Text.resx Sun --> Sunday Mon --> Monday Now I want to get the

• Read data from txt files - using Linq-Entities? 2012-02-28

in my current ASP.net MVC 3.0 project i am stuck with a situation. I have four .txt files each has approximatly 100k rows of records These files will be replaced with new files on weekly bases. I need to Query data from these four text files, I am no

• Windows batch file that reads commands from txt file 2009-11-01

I have this test.txt file with the following content: @echo off wget -q http://subs.ro/get/21518 move 21518 %userprofile%/Desktop/21518.zip %userprofile%/Desktop/21518.zip This file is generated by a javascript and the content keeps changes. I have t

• Reading int value from txt file on SD card android 2010-12-30

So in this app I made, The user makes a project and when they save, the number of frames is saved to numberFrames.txt on the SD card. Then I retrieve the file in another class. Only thing is that nFrames = 50 when i show a toast of nFrames to the scr

• Reading values from a file txt or xml 2011-06-22

I'm developing a simple bpel process that takes data from an external file (txt or xml). In detail, i'm trying to develop a process that takes in input 2 strings (user and pass) and checks if they are in my "Account" file. If so, output return 'true'

• Reading values from property file through NANT 2009-04-28

How can I read a value alone from the property file. For example, how can I read the values of build.home or temp.dir from the below example. contents of env.properties build.home=c:\build temp.dir=c:\temp Regards Sarathy --------------Solutions-----

• How do I use CIN to read values from a file (64 bit integer) 2011-02-20

Let's say I have the file input.txt containing the following numbers : 2 1 1 888450282 1 2 I need to read the first line in separate variables (a,b,c,d). The big value can be big like a 64 bit integer. How do I use C++ IO to do this? And the second l

• Java read values from text file 2011-05-11

I am new to Java. I have one text file with below content. `trace` - structure( list( "a" = structure(c(0.748701,0.243802,0.227221,0.752231,0.261118,0.263976,1.19737,0.22047,0.222584,0.835411)), "b" = structure(c(1.4019,0.486955,-0.127144,0.642778,0.

• Powershell: Read value from xml files 2010-03-22

I need some with help with PowerShell, please. It should be pretty easy: I have a list of subdirectories, with a xml file in each one. I want to open each xml file and print the value of one node. The node is always the same, as the xml files are act