Index each row of one matrix applying an operator/function to the second matrix, then concatenate all the results.

조회 수: 4 (최근 30일)
I'm fairly new to Matlab. I've got the following code where I'm indexing each row of 'a' and adding it to matrix b. Then I concatenate the resultant values:
a = [0 0;100 100];
b = [1 1; 0 0];
c = a(1)+b;
d = a(2)+b;
e = [c;d];
% the result looks like this (which is the correct result I want):
e =
1 1
0 0
101 101
100 100
% Obviously if I try something like this is doesn't work as the matrix dimensions are different:
% e= a(:) + b
What is the best way to do this so that the concatenating and indexing happens automatically? Should I try and figure out a for loop for every row of matrix 'a' or am I missing an easy function or trick here?
The background to why I'm asking is that I've got two much larger matricies that I have to apply something similar: indexing each row of the first matrix and applying an operator/function to the second matrix with the final matrix being a 'concatenation' of the results. I'm hoping if I can figure it for this simple problem as shown above I can apply similar principals to a large dataset.

채택된 답변

madhan ravi
madhan ravi 2020년 7월 25일
z = reshape(a(1:2),1,1,[]) + b;
z1 = squeeze(num2cell(z,[1,2]));
Wanted = cat(1, z1{:})
  댓글 수: 2
Joshua Murray
Joshua Murray 2020년 7월 26일
Thanks for getting me on the right track.
If I wanted to add column 2 of matrix 'a', how would I do this? For example:
% If I changed the second row of 'a' to something like this:
a = [0 0.1;100 100.1];
b = [1 1; 0 0];
z = reshape(a(1:2),1,1,[]) + b;
z1 = squeeze(num2cell(z,[1,2]));
Wanted = cat(1, z1{:})
How do I get the reshape to command to apply to different rows of a (and all columns), as at the moment it only does it for column 1. I've tried changing a few values around in the reshape but I can't figure out how to apply it to different columns.
Joshua Murray
Joshua Murray 2020년 7월 27일
Thanks heaps @madhan ravi.
Please ignore the above reply as I've figure it out now.

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

추가 답변 (0개)

카테고리

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