Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Topic: Merging multiple matrices
Replies: 4   Last Post: May 9, 2013 10:56 AM

 Messages: [ Previous | Next ]
 Steven Lord Posts: 17,965 Registered: 12/7/04
Re: Merging multiple matrices
Posted: May 9, 2013 10:37 AM

"Martijn van Sebille" <m.vansebille@deletethis.tudelft.nl> wrote in message
news:kmgbic\$eg\$1@newscl01ah.mathworks.com...
> "Bruno Luong" <b.luong@fogale.findmycountry> wrote in message
> <kmg9vm\$o98\$1@newscl01ah.mathworks.com>...

>> "Martijn van Sebille" wrote in message
>> <kmg978\$ljp\$1@newscl01ah.mathworks.com>...

>> > Dear,
>> >
>> > I am trying to efficiently merge multiple matrices, combining their
>> > maximal values. For example: If A = [1 1 2; 1 2 1; 2 1 1] and B = [3 1
>> > 1; 1 3 1; 1 1 3], then their maximal values combined would be: C = [3 1
>> > 2; 1 3 1; 2 1 3].

>>
>> C = max(A,B)
>>
>> If you have several, e.g., A1, A2, ...., A100, consider the for loop or
>> using 3d array as temporary variable:
>>
>> C = { A1 , A2, ... A100 }
>> C = max(cat(3,C{:}),[],3);
>>
>> % Bruno

>
> Thank you very much. The last suggestion works very well!
> Do you also happen to know how to construct the C = { A1 , A2, ... A100 }
> struct, without hardcoding the number of elements?

Ideally, avoid creating variables named A1, A2, etc. in the first place.

> At the moment I have 4 elements, so C = { A1, A2, A3, A4 }; However, the
> number of elements depends on other variables in my script, which I would
> like to be able to change. How could I program C so that is flexible like
> that?
> I hope it is clear what I mean.

Either create them as a 3-D array in the first place like C in the code
below, or store them in a cell array (and refer to them as such) as you go
like D.

n = 10;
C = zeros(7, 7, n);
D = cell(1, n);
for k = 1:10
C(:, :, k) = rand(7, 7);
D{k} = randn(4, 5);
end
max(C, [], 3)
max(cat(3, D{:}), [], 3)

--
Steve Lord
slord@mathworks.com