Assign to certain positions of an entire cell array values from another cell array of the same size

3 views (last 30 days)
Dear community,
sorry if this question was answered somewhere but I could not find a solution to exactly this problem and I have not found functions in Matlab that do what I need.
I have a quite simple problem assigning to an entire cell array values from another cell array of the same size. However I want to assign them to a certain and same positions of the cells. I know I can do the for-loop but I want to avoid it.
Example:
I have a cell array
a_part{1} = [1; 2; 8];
a_part{2}=[11; 31; 15];
a_part{3} =[2; 4; 8];
and I would like to assign it to another cell array which is of the same size (1x3) but can be empty for example
a_whole = cell(1,3).
However I want to assign these values to certain (same) positions in an entire a_whole, say to rows [1, 3, 5]. I want to get
a_whole{1} = [1;0;2;0;8];
a_whole{2} = [11;0;31;0;15];
a_whole{3} = [2;0;4;0;8]};
I tried the following:
a_whole{:}([1,3,5],:) = a_part;
a_whole(:)([1,3,5],:) = a_part;
[a_whole{:}([1,3,5],:)] = deal(a_part);
I get different error messages but no result. However, this works nicely:
for i=1:3
a_whole{i}([1,3,5],:) = a_part{i};
end
I hope there is a better solution.
Thanks for help and your time!

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 24 Aug 2016
a_part {1} = [1; 2; 8];
a_part {2} = [11; 31; 15];
a_part {3} = [2; 4; 8];
a = zeros(numel(a_part{1})+2,numel(a_part));
a(1:2:end,:) = [a_part{:}];
a_whole = num2cell(a,1);

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 24 Aug 2016
a_part{1} = [1; 2; 8];
a_part{2}=[11; 31; 15];
a_part{3} =[2; 4; 8]
a_whole = cell(1,3)
out=cellfun(@(x) [x(1) 0 x(2) 0 x(3)],a_part,'un',0)
  3 Comments
Valeria
Valeria on 25 Aug 2016
OK, I just wanted to be free to fill in values to certain predifined positions whatever cell array I had from before. I chose for simplicity to have an empty cell array but I could have had any cell array and wanted my code to work. I did not want to fill zeros in between.
Thanks a lot for trial, I've got already code working.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!