Saving output of for loop after each iteration (for a function)

조회 수: 19 (최근 30일)
JD
JD 2021년 4월 1일
댓글: Image Analyst 2021년 4월 2일
y = 0:0.05:1;
u= 2*y-(2*y.^3)+y.^4;
a = 0:0.01:1;
b = 4000;
Carray=zeros(1,101)
for i=1:size(a)
c=A_function(y,u,b,a(i));
Carray(i)=c;
end
I want to run the function 'c' for all values of 'a'
and I want to store value of 'c' for each 'a'
The error i get is "Unable to perform assignment because the left and right sides have a different number of elements"
Can someone please let me know what I am doing wrong?
Thanks

답변 (2개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 4월 1일
편집: Sulaymon Eshkabilov 2021년 4월 1일
Here is the corrected code of yours:
y = 0:0.05:1;
u= 2*y-(2*y.^3)+y.^4;
a = 0:0.01:1;
b = 4000;
C=zeros(numel(a),numel(u));
for ii=1:size(a)
C(ii,:)=A_function(y,u,b,a(ii));
end
  댓글 수: 3
JD
JD 2021년 4월 1일
I fixed the error by changing this line “For ii=1:size(a)-1”
But now my C matrix is still all 0’s
Steven Lord
Steven Lord 2021년 4월 1일
%{
C=zeros(numel(a),numel(u));
for ii=1:size(a)
%}
I agree with the first line but not the second. Before looking at the output of the code below, how many lines of text does it display?
a = 0:0.1:1;
for k = 1:size(a)
fprintf("k is %d\n", k)
end
k is 1
Now compare this with using numel instead of size.
a = 0:0.1:1;
for k = 1:numel(a)
fprintf("k is %d\n", k)
end
k is 1 k is 2 k is 3 k is 4 k is 5 k is 6 k is 7 k is 8 k is 9 k is 10 k is 11
Why the difference in behavior? When any of the inputs to the colon function or : operator is non-scalar and non-empty, MATLAB will just use the first element of that input.
sz = size(a)
sz = 1×2
1 11
v = 1:sz % equivalent to 1:sz(1)
v = 1
While your code would have worked for a column vector, the numel approach works in general to allow you to loop through all the elements in an array.

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2021년 4월 1일
Try this:
y = 0:0.05:1;
u = 2*y-(2*y.^3)+y.^4;
a = 0:0.01:1;
b = 4000;
rows = length(a)
columns = 101;
Carray = zeros(rows, columns);
for row = 1 : rows
resultVector = A_function(y, u, b, a(row));
Carray(row, :) = resultVector;
end
function c = A_function(y, u, b, aValue)
c = randi(9, 1, 101); % Whatever it may be...
end
Obviously replace the A_function with your actual function that returns a vector. Carray will not be all zeros.
  댓글 수: 8
JD
JD 2021년 4월 1일
Hi Image Analyst,
Did that work for you? I have to turn in my work tonight so just wondering if you were able to troubleshoot why it’s not working with the actual function.
Thanks
Image Analyst
Image Analyst 2021년 4월 2일
Sorry, I didn't get a chance last night, but I guess it's past the homework deadline so it doesn't matter at this point.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by