Extracting data from struct as matrix
13 次查看(过去 30 天)
显示 更早的评论
Hi,
I have the following struct:
S(1).a = 1:5;
S(2).a = 11:10;
S(3).a = 21:27;
Is there a way to vertically concatenate them without looping? I cannot do vertcat(S.a) because data is of different size.
I want output like this [1:5; 11:10; 21:27]
Thank you
2 个评论
Stephen23
2024-6-13
"I want output like this [1:5; 11:10; 21:27]"
Matrices cannot have rows of different lengths.
采纳的回答
Ganesh
2024-6-13
You can consider the following workaround for your problem, without using for loops:
S(1).a = 1:10;
S(2).a = 11:17;
S(3).a = 21:26;
aCell = arrayfun(@(x) {x.a}, S);
% Find the maximum length among all arrays
maxLength = max(cellfun(@numel, aCell));
% Function to pad arrays with NaN to match the maxLength
padFunction = @(x) [x, NaN(1, maxLength - numel(x))];
y = cellfun(padFunction, aCell, 'UniformOutput', false);
y = vertcat(y{:})
2 个评论
Stephen23
2024-6-14
Alternatively doanload PADCAT here:
and use it like this:
S(1).a = 1:5;
S(2).a = 10:11;
S(3).a = 21:27;
M = padcat(S.a)
更多回答(2 个)
Jonas
2024-6-13
编辑:Jonas
2024-6-13
as you already said, you canot concatenate the data as matrix, since it has different size. you could use a cell array, but this would be no better than the struct. another possibility coul be to pad shorter variables with NaN. but here, you would need a loop.
S(1).a = 1:5;
S(2).a = 11:10;
S(3).a = 21:27;
sizes=arrayfun(@(in) length(in.a),S);
maxSize=max(sizes);
asMatrix=nan(numel(sizes),maxSize);
for sNr=1:numel(S)
asMatrix(sNr,1:sizes(sNr))=S(sNr).a;
end
asMatrix
0 个评论
Shivani
2024-6-13
编辑:Shivani
2024-6-13
This question seems similar to https://www.mathworks.com/matlabcentral/answers/2128126-extracting-data-from-struct-as-array?s_tid=answers_rc1-1_p1_MLT
You will need to modify the solution in the above answer as seen in the below code snippet to obtain the desired result.
S(1).a = 1:5;
S(2).a = 11:15;
S(3).a = 21:25;
M = vertcat(S.a)
Please note that the ranges you have provided cannot be concatenated vertically because they will not be of the same length. I am therefore assuming the ranges to be 1:5, 11:15 and 21:25. Since they all contain 5 elements, we can concatenate them to a matrix containing 5 columns.
Hope this helps!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!