Adding a column to my table
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Austin
am 15 Sep. 2023
Kommentiert: Austin
am 15 Sep. 2023
I am still quite new to Matlab, but I have a table where I am trying to add a column of 1 through k with k being the number of rows. The code I am using to set up the table is:
P = 'Filepath';
S = dir(fullfile(P,'*.csv'));
S = natsortfiles(S);
for k = 1:numel(S)
F = fullfile(P,S(k).name);
S(k).data = csvread(F,245,230,[245 230 245 230]);
end
then I am trying to add a column at the end with:
S.time = transpose([1:k]);
but it keeps returning this error: Scalar structure required for this assignment.
How can I fix this?
2 Kommentare
Stephen23
am 15 Sep. 2023
Bearbeitet: Stephen23
am 15 Sep. 2023
"but I have a table ..."
Where?
The deprecated function CSVREAD returns a numeric matrix, whereas DIR returns a structure array. I do not see anywhere in your code where you would have a table.
"...where I am trying to add a column of 1 through k with k being the number of rows"
The number of rows of what exactly?
Note that k is the loop iterator, which here basically just tells your code to process the 1st, 2nd, 3rd, ... Nth file found by your DIR call. It is therefor unclear what k has to do with "time" or "rows".
If the aim is to add this field to the structure S:
S(1).time = 1;
S(2).time = 2;
S(3).time = 3;
..
S(N).time = N;
then all you are doing is replicating the implicitly defined indices of that structure array.
Note that square brackets are a concatenation operator whereas COLON generates a vector. So with this code:
[1:k]
you generate a vector using the COLON and then concatenate that vector with absolutely nothing else to obtain exactly the same vector. Why do you need to perform a superfluous concatenation of a vector with nothing else to get exactly the same vector?
In any case, lets try to figure out what you want to achieve. Given this structure array:
S(1).name = 'hello.csv';
S(1).date = '2023/09/15';
S(2).name = 'world.csv';
S(1).date = '2023/09/15';
please show the exact output that you want to obtain.
Akzeptierte Antwort
Cris LaPierre
am 15 Sep. 2023
Bearbeitet: Cris LaPierre
am 15 Sep. 2023
You have defined S as a multidimension structure (S(k)), not a table, so in order to add time to your structure, you must now include an index: S(1).time
for k = 1:2
S(k).data = rand(5);
end
S(1).time = 1:10;
S(1)
S(2)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Tables finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!