Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Hello can somebody tell me what I am doing wrong?

1 回表示 (過去 30 日間)
D'Monte Pittman
D'Monte Pittman 2015 年 7 月 16 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
I am trying to write a MATLAB program using a forloop to determine the number of values that are positive, negative, and the number of values that equal zero in a vector containing 'N' elements. I can't get it to work.
format compact
v = input('Enter the number of elements in the Vector: ');
a = input('Enter the Array:');
for i = 1:length(a)
if v > 0
fprintf('v>0',i)
elseif v < 0
fprintf('v<0',i)
else
fprintf('v=0',i)
end
end

回答 (2 件)

Jos (10584)
Jos (10584) 2015 年 7 月 16 日
This is a working for-loop, which prints out something that resembles your goal:
a = input('Enter the Array:');
for i = 1:length(a)
v = a(i) ; % get the i-th element of a
if v > 0
fprintf('v>0',i)
elseif v < 0
fprintf('v<0',i)
else
fprintf('v=0',i)
end
end
However, the next step is to learn to do this in a matlab-like way
V = input('Enter the Array:');
disp('V < 0') ;
idx = find(V<0) ; % all at once
disp(idx) ;

Muthu Annamalai
Muthu Annamalai 2015 年 7 月 16 日
Hi Pittman,
In addition to the answer by Jos, I have some observations for you:
  1. Enter the data at your runtime as '5', and '[1,2,3,4,5]' (not including the quotes ofcourse)
  2. When you use fprintf see MATLAB documentation , you want code like,
fprintf('v < 0 : %d',i);
Ofcourse your code is written in a more C-like fashion, whereas using MATLAB we like to vectorize operations since matrices are native types.
HTH.

この質問は閉じられています。

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by