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

37 次查看(过去 30 天)
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

回答(1 个)

dpb
dpb 2023-9-13
编辑:dpb 2023-9-13
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 个评论
Walter Roberson
Walter Roberson 2023-9-14
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Import and Analysis 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by