How to reference multiple matrices in cell arrays using a colon or other special characters rather than a loop?

4 views (last 30 days)
Is there a way to pull values from multiple arrays without using loops? Specifically, I would like to achieve something like this:
for i = 1:5
for j = 1:3
new{i,j} = a1{i,j}./a2{i,j};
end
end
by doing something simpler and faster like:
new{:,:} = a1{:,:}./a2{:,:};
but this kicks back an error. Assuming all the cell arrays hold appropriately sized matrices, is a loop my only option for this?

Accepted Answer

dpb
dpb on 29 Dec 2015
Edited: dpb on 30 Dec 2015
That's what cellfun is for...
>> a={rand(2)}; a(2)=a(1); % a simple test
>> b=a;
>> cellfun(@rdivide,a,b,'uni',0)
ans =
[2x2 double] [2x2 double]
>> ans{:}
ans =
1 1
1 1
ans =
1 1
1 1
>>
ADDENDUM TO ALTERNATE CONSTRUCTS REQUESTED:
Subscripted assignment
out=cellfun(@(x) x(1:2:end,1:2:end),a,'uni',0);
for fixed subscripts. To include them as a variable, add as additional dummy arguments in the anonymous function definition. Assignment is kinda' the "odd man out" as you see; there isn't another function name as a standin is for other operators such as plus
The interp2 case. Presuming X?,Y? are fixed, then
new=cellfun(@(x) interp2(Xl,Yl,x,Xh,Yh,'cubic'), a, 'uni',0);
The pattern should begin to come apparent; if the operation is a basic one equivalent to a single operation like + you use that function handle name; if it's more complex you invoke another function placing the cell array(s) in the passed-in position(s) in order they're given. Here the operation is simple enough to use an anonymous function; if it's more complex, write a separate function in an m-file and use the handle to it instead.
Seems very complicated at start, granted, but once you get one or two under your belt it'll quickly become easier...
  2 Comments
Stephen23
Stephen23 on 31 Dec 2015
Selena G's comment moved here:
That was very helpful, but I am a beginner when it comes to function handles. How would I apply that for something like this:
for i = 1:5
for j = 1:3
new{i,j} = interp2(Xl,Yl,a1{i,j},Xh,Yh,'cubic');
end
end
or this:
for i = 1:5
for j = 1:3
new{i,j} = a1{i,j}(1:2:10,1:2:10);
end
end

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!