how do I use importdata() to import specific columns of data from a .txt file?

18 views (last 30 days)
The file is called bubbles.txt and has been attached to this question. I'm trying to import the hours accessed and cumulative bubbles columns, however, I am not completely sure how to proceed. So far my code looks like this:
clear all; close all; clc
M = importdata('bubbles.txt', ' ', 1);
for k = [1, 3]
disp(M.colheaders(1, k))
disp(M.data(:, k))
disp(' ')
end
This returns an error saying:
Dot indexing is not supported for variables of this type.
Error in lab8t2 (line 9)
disp(M.colheaders(1, k))
How can I solve this issue?
Regards

Answers (1)

dpb
dpb on 13 Sep 2023
Edited: dpb on 13 Sep 2023
importdata returns an array, not a struct nor table -- it has its uses, but I generally avoid it for more specific functions that do what really want. There's no real reason to not just read the file instead of getting too fancy; here a table would seem appropriate--
tBubbles=readtable('bubbles.txt');
Warning: Column headers from the file were modified to make them valid MATLAB identifiers before creating variable names for the table. The original column headers are saved in the VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.
head(tBubbles)
PhotoNumber HoursElapsed Bubbles CumulativeBubbles ___________ ____________ _______ _________________ 1 1 117 117 2 2 96 213 3 4 180 393 4 6 128 521 5 8 115 636 6 10 94 730 7 12 94 824 8 14 67 891
and you've got everything...and now dot indexing will return the respective data you want directly...
plot(tBubbles.HoursElapsed,tBubbles.CumulativeBubbles)
xlabel('Hours'), ylabel('Number Bubbles (Total)')
for example...
  2 Comments
Walter Roberson
Walter Roberson on 14 Sep 2023
importdata() can return any of three different datatypes, depending on what data it finds in the file. I recommend against using it, recommending that instead you use a function such as readtable() that returns predictable datatype.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!