Info
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
the For loop
조회 수: 2 (최근 30일)
이전 댓글 표시
is i put
put a=(1:1:10)
k=a*b
end
but when i run it,work space say a min and max value is both 10. why? is there anyway other way to do it?
댓글 수: 0
답변 (2개)
Walter Roberson
2011년 11월 30일
What shape is b ? Unless b is a scalar constant, the "*" would be interpreted as matrix multiplication; you would use .* for element-by-element multiplication. For more information please see the reference material for mtimes and times .
Also, "put" is not MATLAB command. If the actual word you have there is "for", as in
for a=(1:1:10)
k=a*b
end
then you have a different situation. The for loop sets the loop variable ("a" in this case) to each value in turn, so each execution of the loop would involve a scalar value for "a", multiplied by "b". The loop would then overwrite the current value of k (as it appears alone on the left hand side), so at the end of the loop the value of k would be the same as if the loop had only been executed once with "a" being the maximum value (10) . Possibly the code you want is
A = 1:1:10;
for a = 1:length(A);
k(a) = A(a) .* b;
end
At the end of a "for" loop, the loop variable will only have a single scalar value, the value that it had at the time the loop finished.
Possibly the code you want is
a = 1:1:10;
k = a .* b;
with no loop.
댓글 수: 2
Image Analyst
2011년 12월 1일
kevin: Try this code. It will calculate e for all those possibilities of a, and d and plot e. It will then find the index where e is minimum and report the values of a and b there at the min (for just the specific, discrete values of a and b used, not for any continuous-values of a and b):
e_index = 1;
for a = 1 : 10
for d = 2 : 5
% Get and store a and b for this iteration.
a1(e_index) = a;
b(e_index) = cos(a)*12;
% kevin never uses c at all!
c = sin(a)/2;
% Calculate e for these values of a, b, and d.
e(e_index) = a * b(e_index) * 5 / d;
% Increment to the next element in e.
e_index = e_index + 1;
end % of "d" loop
end % of "a" loop
plot(e);
grid on;
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1])
[min_e_value, min_e_index] = min(e);
bAtMinE = b(min_e_index);
aAtMinE = a1(min_e_index);
fprintf('e has a min value of %f at element %d,\nwhich occurs for a = %d and b = %f.\n',...
min_e_value, min_e_index, aAtMinE, bAtMinE);
Results in command window:
e has a min value of -251.721459 at element 37,
which occurs for a = 10 and b = -10.068858.
댓글 수: 0
이 질문은 마감되었습니다.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!