4 Matlab code snippets to edit tables

In this short article, I want to share some of most useful code snippets of Matlab for editing tables and data. Using these codes, you can change data or structure the tables for using in your learning applications.

How to read an Excel table and store it in Matlab variable

Using the code below you can read Excel table BM and store it in variable A. Note that table file must be in the same directory.

A = readtable('BM.xlsx')

How to move a table column in Matlab

Using this code you can move Table column M after column K. A is the table variable.

A = movevars(A,'M','After','K');

How to edit string data in a Table in Matlab

Imagine you have a table that has some file names stored in it. For example Matlab’s image processing app stores not only file names but also complete path to that file. In this case, you’d better omit the path and keep only the file name. You can do this with the following code.

This code replaces the strings in all rows (:) of 1st column of table A. It replaces ‘c:\users’ with an empty space” which equals deleting it. You can also use this method to omit spaces in a table.

A{:, 1} = regexprep(A{:, 1}, 'C:\users', '');

How to combine 2 columns in a Matlab table

Using the code below you can combine columns W and R into a single column TB.

A = mergevars(A,{'W','R'},'NewVariableName','TB');

That’s all,
I hope 4 Matlab code snippets to edit tables will save you some time

Leave a Reply

Your email address will not be published.