Create a table from vectors with different rows and fill missing
1 次查看(过去 30 天)
显示 更早的评论
I have a number of vectors for several dates with different lenghts
- 01/06/2022: 478 rows
- 02/06/2022: 531 rows
- 03/06/2022: 502 rows
- ...
I would like to add them to one array in order to plot them afterwards.
For this, they need to be the same rows.
I was thinking to create an array with set rows A = 0:500 and for example add the first 500 values.
The vectors with less would be filled with 'Nan' and the vectors with more would be cut short.
How could I do this in a loop?
1 个评论
Mario Malic
2022-9-1
Here's a minor example that you can expand yourself
a = ones(400, 1);
b = ones(450, 1);
c = ones(500, 1);
vecDim = max([numel(a), numel(b), numel(c)])
a(end + 1 : vecDim, :) = nan;
回答(1 个)
Arjun
2024-9-11
Hi,
I see that you have several vectors of different length and now you want to stack them together in an array of fixed length which may require either truncation or filing in “NaN” values.
First, collect all your vectors into a cell array to facilitate easy access and iteration. Decide on a fixed number of rows for the final matrix, which will be the maximum number of elements you wish to retain from each vector. Initialize a result matrix with these dimensions, filling it with “NaN” values to handle any missing data. As you iterate over each vector, determine how many elements can be copied—either the full length of the vector or up to the specified number of rows, whichever is less. Copy this data into the corresponding column of the result matrix. If a vector is shorter, the remaining positions will naturally remain as “NaN”, preserving the matrix's structure.
Please look at the code below for better understanding:
% Example vectors for different dates
data1 = rand(478, 1); % Example data for 01/06/2022
data2 = rand(531, 1); % Example data for 02/06/2022
data3 = rand(502, 1); % Example data for 03/06/2022
% List of vectors, it will ease out the iteration over vectors
dataList = {data1, data2, data3};
% Desired number of rows
numRows = 500;
% Initialize the matrix to store the results
numVectors = length(dataList);
resultMatrix = NaN(numRows, numVectors);
% Loop through each vector
for i = 1:numVectors
currentData = dataList{i};
len = min(length(currentData), numRows); % Determine the length to copy
% Truncate or pad with NaN
resultMatrix(1:len, i) = currentData(1:len);
end
We have the desired values stored in the “resultMatrix” which can be used for the plotting task afterwards.
I hope it will help!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!