Output Structure Values Of Unequal Length To A Matrix
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Deepak
le 6 Sep 2024
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 commentaire
Voss
le 7 Sep 2024
Modifié(e) : Voss
le 7 Sep 2024
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)]
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!