can any body help me how to use "arrayfun" to update parameter with in "for loop"? is it possible?

example problem i want to solve
function q=initial(p,cn)
for i=1:100
s(i,1)=(25400/cn(i,1))-254;
q(i,1)=(((p(i,1)-0.2*s(i,1)).^2)./(p(i,1)+0.8*s(i,1)));
s(i+1,1)=s(i,1)+(0.1*q(i,1));
end
%%i want to update the "s" value in each iteration
p=gpuArray(randi([0 5],100,1));
cn=gpuArray(randi([70 85],100,1));
a=arrayfun(@initial,p,cn);
%%this is how i want to use "arrayfun"

 Akzeptierte Antwort

That's not the way arrayfun works. arrayfun passes each element of your input arrays to the function, so you cannot then index those arrays.
What you are doing appears to be creating an inherently serial loop with a dependency between each iteration and the previous one. However, you compute s(i+1) and then immediately erase it in the next loop iteration when i is incremented, so that value doesn't ever reach the output. If you eliminate that line, which seems superfluous, you can get your output q:
function q=initial(p,cn)
s=(25400/cn)-254;
q=(((p-0.2*s).^2)./(p+0.8*s));
end
%%i want to update the "s" value in each iteration
p=gpuArray(randi([0 5],100,1));
cn=gpuArray(randi([70 85],100,1));
a=arrayfun(@initial,p,cn);

3 Kommentare

Hello Joss Knight, can you please help me to solve same type of problem (may actual problem is similar to this problem)
function [s,q]=initial(p,cn)
if cn<5
s=100./cn;
q=s+p;
cn(2,1)=s+2;
else
s=500./cn;
q=s+p;
cn(2,1)=s+4;
end
p=gpuArray([4;5;7;8;7;8;7;2]); cn=gpuArray([15;2;3;4;5;6;7;8]);
[s,q]=arrayfun(@initial,p,cn)
Initially i know only "cn(1,1)"(Input) but to make all inputs of same size i have assumed cn(2:8,1) randomly. so is it possible to get cn(i+1,1) from s(i,1) in the above problem, which means updating "cn" value for next iteration. if not can you please suggest me any other function n matlab which can solve the above problem which is able to use parallel computations in GPU. Thank you
Sorry, I don't understand the question. Try reading the documentation and experimenting with your code.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by