How to reshape every cell in a structure

Hi,
I am trying to reshape every cell in a 1x4 structure with 10 fields. A simplified example would look like this but when I try to reshape every 1x48 cell into 4x12 cells I get the following error: Inputs to STRUCTFUN must be scalar structures.
b = struct('a', {[1:48], [1:48], [1:48], [1:48]})
structfun(@(a) reshape(a, 12, 4), b, 'UniformOutput', false)
Thoughts ?

 Accepted Answer

arrayfun(@(x) reshape(b(x).a, 12, 4), 1:numel(b), 'UniformOutput', false)

6 Comments

Note: You’re reshaping them into 12 X 4 to make it 4 X 12 just swap 12 and 4.
This works great for one field (in this case a) but lets say I have 10 fields. How do I apply this to all fields ?
If you have different named fields for example, then looping through fieldnames is one option. If it’s a(1) ,a(2) and so on again looping should do the trick.
Mmmm, something like this ?
b = struct('a', {[1:48], [1:48], [1:48], [1:48]})
fn = fieldnames(b);
for k = 1:length(fn)
j = char(fn(k))
b = arrayfun(@(x) reshape(b(x).j, 4, 12), 1:numel(b), 'UniformOutput', false)
end
fn = fieldnames(b);
for k = 1:numel(b)
for l = 1:numel(fn)
b(k).(fn{l})= reshape(b(k).(fn{l}), 4, 12);
end
end
Great, thank you.

Sign in to comment.

More Answers (0)

Categories

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

Tags

Asked:

on 15 Aug 2019

Commented:

on 15 Aug 2019

Community Treasure Hunt

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

Start Hunting!