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

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?

 採用された回答

dpb
dpb 2015 年 12 月 29 日
編集済み: dpb 2015 年 12 月 30 日
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 件のコメント

Stephen23
Stephen23 2015 年 12 月 31 日
Selena G's "Answer" moved here:
Ah, very cool. Thank you.
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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2015 年 12 月 29 日

コメント済み:

2015 年 12 月 31 日

Community Treasure Hunt

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

Start Hunting!

Translated by