How to add values from two different arrays into a matrix
8 views (last 30 days)
Show older comments
I'm trying to figure out how to add values from a 1Xn double to a mX1 double such that it populates a matrix of mXn by adding consecutive column values to the entire row. An example here would be
a = [1 2] (1xn)
and
b = [1;2;3] (mx1)
gives
c=[2 3; 3 4; 4 5](mxn).
My actual example contains much larger a's and b's. In addition, its not clear to me how MatLab views what it calls 1xn double or mx1 double. Does matlab see these as arrays or matrices? Apologies in advanced if my question isn't clear. Thank you!
Accepted Answer
Bob Thompson
on 1 Feb 2018
Matlab sees them as either arrays or matrices, depending on the type of operations you use them for. Unfortunately I do not do much work with matrices so I don't typically use their operations, but I know that is essentially how you define the difference for matlab.
My suggestion for adding in that manner would be to use a for loop to only add one row or column at a time. There is probably a faster way of doing this, but I am not an expert on matlab matrix operations.
for i = 1:length(b);
results(i,:) = a + b(I);
end
More Answers (1)
James Tursa
on 1 Feb 2018
Edited: James Tursa
on 1 Feb 2018
On later versions of MATLAB:
c = a + b;
On earlier versions of MATLAB:
c = bsxfun(@plus,a,b);
In MATLAB, variables have a size that contains at least two dimensions always. It could be that one or more of those dimensions is 1, in which case there are standard names used:
scalar --> a "1 x 1" variable
vector --> a "m x 1" column vector or "1 x n" row vector
matrix --> a "m x n" variable
array --> a "m x n x p x ..." variable
To add (+) or subtract (-) or element-wise multiply (.*) or element-wise divide (./) or element-wise take power (.^) two variables, they need to be of conforming size. In older versions of MATLAB, that meant the variables needed to be exactly the same size or at least one of them needed to be a scalar. To do the "expansion" type of operation you wanted needed a special function such as bsxfun. On later versions of MATLAB, however, this expansion happens automatically. That is, any dimension that is 1 is "virtually expanded" to match the dimension of the other operand ... it is as if you did appropriate repmat operations on the operands to get them to a minimum conforming size and then did the operation.
2 Comments
James Tursa
on 2 Feb 2018
Edited: James Tursa
on 2 Feb 2018
"... I think I did not provided enough information ..."
No. In fact you provided all the information needed to solve the problem. The two methods I posted are the standard way of doing this in MATLAB without writing explicit loops. They give the same result as the looping method you accepted.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!