Can I input data with multiple column lengths into one matrix?
36 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I am trying to import data from multiple .txt files, each file has two columns but each file has a different and unknown number of rows. The number of files also differs each time I have to run the script, and so I was wanting to be able to just to set a variable to the number of files, and then import the data inside a loop:
for i=1:numSlugs
slugfilename = strcat(filename,slugarray(i),extension);
data = importdata(slugfilename);
t(:,i) = data.data(:,1);
x(:,i) = data.data(:,1);
end
Error: Unable to perform assignment because the size of the left side is 300-by-1 and the size of the right side is 84-by-1.
Error in TXT_to_Graph_Auto (line 41)
t(:,i) = data.data(:,1);
Is there a way I can make a matrix with different sized columns or a way to use t = zeros(300,numslugs) since each file will not have more than 300 rows?
Edit: I fixed it, I was able to add another for loop:
for i=1:numSlugs
slugfilename = strcat(filename,slugarray(i),extension);
data = importdata(slugfilename);
[R,C] = size(data.data);
for j=1:R
t(j,i) = data.data(j,1);
x(j,i) = data.data(j,2);
end
end
This works, and just has 0's as fillers in the rest of the rows of the columns that have a smaller number of rows.
0 commentaires
Réponses (2)
John D'Errico
le 26 Fév 2022
Modifié(e) : John D'Errico
le 26 Fév 2022
No. Sorry, but no. A matrix cannot have columns that vary in length. A matrix in MATLAB is a rectangular array of scalar elements. Could you define your own class that does what you want? UGH. But yes.
Could you fill the shorter columns with something that would be a non-number, like a NaN? Well, yes. As long as you know in advance the length of the longest column. You would still have garbage at the end of the shorter columns though. But why bother?
What can you do that is simple? Simplest is to use a cell array. The cells of a cell array can be any size at all, since they can store anything.
help cell
0 commentaires
David Goodmanson
le 26 Fév 2022
Modifié(e) : David Goodmanson
le 26 Fév 2022
Hi Brice,
If you preallocate as you mentioned then you can insert each column with
t = zeros(300,numslugs);
x = zeros(300,numslugs);
u = zeros(1,numslugs);
for i = 1:numslugs
(get the data)
[nrow ncol] = size(data.data(:,1));
t(1:nrow,i) = data.data(:,1);
x(1:nrow,i) = data.data(:,2); <-- not(:,1), it appears
u(i) = nrow;
end
where u was added in case you want to keep track of the number of elements in each row.
0 commentaires
Voir également
Catégories
En savoir plus sur File Operations dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!