Output Structure Values Of Unequal Length To A Matrix
3 次查看(过去 30 天)
显示 更早的评论
Lets say I have a structure (st) of of three runs depicted below which contains the following fields: run, x and y. run is only a scalar and x & y are the same length for each corresponding run. The following code is an example
st(1).run = 1; st(1).x = [0:2]'; st(1).y = 1*st(1).x;
st(2).run = 2; st(1).x = [5:7]'; st(2).y = 2*st(2).x;
st(3).run = 3; st(1).x = [0:2]'; st(3).y = 3*st(3).x;
I can generate the output that combines the entire structure into one matrix by using the following code which works
rightOutputMat = [];
for i = 1:length(s)
tempRun = ones(length(st(i).x),1)*st(i).run;
rightOutputMat = [rightOutputMat; tempRun st(i).x st(i).y];
end
However is it possible to generate an output vector without using a for loop. For example i can use the following to concatenate st.x & st.y into one matrix
outputMat = [vertcat(st.x) vertcat(st.y)];
but I am struggling to include the run number since it is only a scalar with length of 1 and x & y are the same lengths for
Thanks
0 个评论
回答(1 个)
Deepak
2024-9-6
To my understanding, you have created a structure that contains three fields: “run”, “x”, and “y”. Now, you want to combine the entire structure into one matrix without explicitly using a “for” loop.
To accomplish this task, we can use “repmat” and “arrayfun” functions in MATLAB to replicate and concatenate the scaler value “run”, converting it into a cell array containing row vectors of dimension 3x1. Now that all three fields of the structure have same dimensions, we can concatenate them into one matrix by using “vertcat” function.
Below is the complete MATLAB code that solves the task:
% Define the structure array
st(1).run = 1; st(1).x = (0:2)'; st(1).y = 1 * st(1).x;
st(2).run = 2; st(2).x = (5:7)'; st(2).y = 2 * st(2).x;
st(3).run = 3; st(3).x = (0:2)'; st(3).y = 3 * st(3).x;
% Use arrayfun to replicate the run number and concatenate results
runColumn = arrayfun(@(s) repmat(s.run, length(s.x), 1), st, 'UniformOutput', false);
outputMat = [vertcat(runColumn{:}), vertcat(st.x), vertcat(st.y)];
% Display the result
disp('Output Matrix:');
disp(outputMat);
Please find attached the documentation of functions used for reference:
I anticipate this will solve the problem.
1 个评论
Voss
2024-9-7
编辑:Voss
2024-9-7
Another option:
st(1).run = 1; st(1).x = (0:2).'; st(1).y = 1 * st(1).x;
st(2).run = 2; st(2).x = (5:7).'; st(2).y = 2 * st(2).x;
st(3).run = 3; st(3).x = (0:2).'; st(3).y = 3 * st(3).x;
outputMat = [repelem(vertcat(st.run),arrayfun(@(s)numel(s.x),st),1) vertcat(st.x) vertcat(st.y)]
另请参阅
类别
在 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!