How to pass arguments from a matrix to a function?

조회 수: 1 (최근 30일)
Jacky Jo
Jacky Jo 2015년 10월 30일
답변: Walter Roberson 2015년 10월 30일
Hi,
I tried a lot to pass the elements of two matrixes (one by one) to a function which I created. I am not sure whether it is possible to call each element by element of a matrix to a function as a argument. Could you check and give an idea.?
I don't wanna use for loops anywhere in the code. I am trying to do by vectorized way.
Code is given below: Here Ylm(L_or_M,Lo,Co) is a function. instead of that you can use any random function which can give an output of 6x6 matrix.
L_or_M=5;
Co_latitude_grid=1:5;
Longitude_grid=5:8;
MaxLoop= length(Co_latitude_grid)*length(Longitude_grid);
Lo =repmat(Longitude_grid,length(Co_latitude_grid),1) % First matrx which has to be passed element by element
Co =repmat(Co_latitude_grid',1,length(Longitude_grid))% Second matrx which has to be passed element by element
Y_grid(6,6,MaxLoop)=zeros; % initilazation
Lo(Lo(1:1:end))
Y_grid(1:1:end) = Ylm( L_or_M,Lo(1:1:end),Co(1:1:end)); % Ylm() can be changed in to any arbitary function
% which can use Lo & Co matrix's elements one by one
% and produces a 6x6 matrix.

채택된 답변

Walter Roberson
Walter Roberson 2015년 10월 30일
result = arrayfun(@(L,C) Ylm(L_or_M, L, C), Lo, Co, 'Uniform, '0);
This is pretty much equivalent to
result = cell(size(L));
for K = 1 : numel(L)
result{K} = Ylm(L_or_M, Lo(K), Co(K));
end
Notice a cell array is being produced: this is necessary because you indicated that the function produces a 6 x 6 output. If the function produces a scalar output instead then
result = arrayfun(@(L,C) Ylm(L_or_M, L, C), Lo, Co);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by