How do I extract a structure array from a single dynamic structure without using for loops?

4 views (last 30 days)
Im trying to derive a structure array from a single structure without using for loops.
1) I make n copies of the original structure, primal
primalSP = repmat(primal,n,1)
2) I have n sets of m states in the struct primal.states. The size of primal.states is (n*m, nodes) . I want the first set of m states to go to the first structure array, and the second set to the second structure array and so on until all n sets are assigned, like this
primalSP(1).states = primal.states(1:n,:);
primalSP(2).states = primal.states(n+1:2*n,:);
...
Is there a way to do this without a for loop where n is dynamic?
  3 Comments
Shelley Snider
Shelley Snider on 5 Jun 2023
I'm failiar with those functions. I'm having a hard time understandng how to put them together to get what I want.
Stephen23
Stephen23 on 5 Jun 2023
"I want the first set of m states to go to the first structure array, and the second set to the second structure array and so on until all n sets are assigned"
Then your example should be:
primalSP(1).states = primal.states(1:m,:);
primalSP(2).states = primal.states(m+1:2*m,:);

Sign in to comment.

Accepted Answer

Matt J
Matt J on 6 Jun 2023
Edited: Matt J on 6 Jun 2023
There is no way to avoid for-loop speed when dealing with structs and cells. Below is a way to abbreviate the syntax, but both num2cell.m and mat2cell.m have for-loops within them, as you will see if you read those files.
stateCell = num2cell(primal.states,1);
[primalSP(1:n).states] = deal(stateCell{:});

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!