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

1 次查看(过去 30 天)
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!

采纳的回答

Andrei Bobrov
Andrei Bobrov 2016-8-24
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);

更多回答(1 个)

Azzi Abdelmalek
Azzi Abdelmalek 2016-8-24
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 个评论
Valeria
Valeria 2016-8-25
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by