Filter löschen
Filter löschen

Cellfun or for loop

1 Ansicht (letzte 30 Tage)
Atreyu91
Atreyu91 am 26 Aug. 2015
Beantwortet: Guillaume am 26 Aug. 2015
I have the following code where I am trying to obtain U for every k value and the values in a cell array:
G = 1x3 cell
If
G{1,1} = [-6.45230249676815e-06;
2.43528862745912e-20;
2.00553181084869e-19;
6.45309629402509e-06;
-9.16814514353228e-20;
6.45627245974903e-06]
G{1,2} = [-3.22654814674929e-06;
-5.38986674121538e-20;
-2.25622328702039e-20;
3.22734209049890e-06;
-2.25622301386590e-20;
3.23051981960359e-06]
G{1,3} = [-2.15129672917826e-06;
-2.05328256780239e-20;
-6.68510603470547e-21;
2.15209081944770e-06;
-6.68510421367576e-21;
2.15527011276720e-06]
and
k = 0.0012
k = 0.0025
k = 0.0037
L1 = 0.1
L2= 0.2
L3 = 0.4
U1 = G(1)*exp(-k*L1)+G(2)*exp(-k*L1);
U2 = G(3)*exp(-k*L1)+G(4)*exp(-k*L1);
U3 = G(5)*exp(-k*L1)+G(6)*exp(-k*L1);
I need to obtain U1,U2,U3 for each value of k
I have tried using for loops and cellfun() etc.
U1 = cellfun(@(G, k) G(1)*exp(-k*L1)+G(2)*exp(-k*L1), G, k, 'UniformOutput', 0);
but it keeps saying "Error using cellfun Input #3 expected to be a cell array, was double instead."
Can anyone please show me how to perform this in MATLAB?

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 26 Aug. 2015
Your description is unclear. One interpretation is that you want
nG = length(G);
kvals = [0.0012 0.0025 0.0037];
nk = length(kvals);
L = [0.1 0.2 0.4];
U = zeros(nk, nG);
for Gidx = 1 : nG
g = G{Gidx};
for kidx = 1 : nk
k = kvals(kidx);
U(kidx, Gidx) = g(2*kidx-1)*exp(-k*L(kidx)+g(2*kidx)*exp(-k*L(kidx));
end
end
but another possibility is that you want all combinations of L used with all combinations of k rather than corresponding L used with each k.
  1 Kommentar
Atreyu91
Atreyu91 am 26 Aug. 2015
Ah yes, it is meant to be L1 in U1 L2 in U2 And L3 in U3 Thought I fixed that

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Guillaume
Guillaume am 26 Aug. 2015
k = 0.0012
k = 0.0025
k = 0.0037
One would assume that's not what you've entered in matlab (since that would result in just k = 0.0037) but something else. For your cellfun to work, you'd have to have written k as a cell array:
k = {0.0012; 0.0025; 0.0037};
The error is clear your third input (k) is not a cell array.

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by