adding data from one cell array to a matrix

M is a 2x4matrix
H is a 3x4cell array
How do i add the 1st row of H to every row of M?
M = [
1 2 3 4
5 6 7 8
];
H = {[15 35] [10 20] [30 40 10] [15]
[30 20 15] [45 55] [50 70] [30 70]
[25] [10 20 30] [25 35] [60 70]};
fun = @(m,h) [fliplr(h)+m,m,m+h];
ans=cellfun(fun,num2cell(M), *H{1,:}*,'Uni',0); < what do i put H as?
ans={[36 16 1 16 36] [20 12 2 12 22] [13 43 33 3 33 43 13] [19 4 19]
[40 20 5 20 40] [26 16 6 16 26] [17 47 37 7 37 47 17] [23 8 23]}

댓글 수: 2

Stephen23
Stephen23 2017년 11월 29일
Do not use ans as the names of any variable. It is a special variable that can be overwritten by MATLAB.
Joseph Lee
Joseph Lee 2017년 11월 29일
It is ok, its not being used in the code itself, its in here just to predict the results in theory

댓글을 달려면 로그인하십시오.

 채택된 답변

Stephen23
Stephen23 2017년 11월 29일
편집: Stephen23 2017년 11월 29일

1 개 추천

If M has two rows then
H([1,1],:)
In general
H(ones(1,size(M,1)),:)
or
repmat(H(1,:),size(M,1),1)

댓글 수: 3

Joseph Lee
Joseph Lee 2017년 11월 29일
편집: Joseph Lee 2017년 11월 29일
Thanks!
Demonstration:
M = [1,2,3,4;5,6,7,8];
H = {[15,35],[10,20],[30,40,10],[15];[30,20,15],[45,55],[50,70],[30,70];[25],[10,20,30],[25,35],[60,70]};
fun = @(m,h) [fliplr(h)+m,m,m+h];
tmp = H(ones(1,size(M,1)),:);
C = cellfun(fun,num2cell(M),tmp, 'Uni',0);
Giving:
>> C{:}
ans =
36 16 1 16 36
ans =
40 20 5 20 40
ans =
22 12 2 12 22
ans =
26 16 6 16 26
ans =
13 43 33 3 33 43 13
ans =
17 47 37 7 37 47 17
ans =
19 4 19
ans =
23 8 23
>>
Joseph Lee
Joseph Lee 2017년 11월 29일
편집: Joseph Lee 2017년 11월 30일
wow thanks again, you predicted what i was going to ask, since my M is meant to be a much larger sized matrix
eg M= 400x1300
H= 10x1300
row=1;
while row<=10
fun = @(m,h) [fliplr(h)+m,m,m+h];
tmp = H(ones(1,size(M,1)),:); <i changed this to do it for increasing rows of H
C{row}= cellfun(fun,num2cell(M),tmp, 'Uni',0);
row=row+1;
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

질문:

2017년 11월 29일

편집:

2017년 11월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by