Using range in a vector

7 ビュー (過去 30 日間)
ck poon
ck poon 2019 年 3 月 21 日
コメント済み: madhan ravi 2019 年 3 月 21 日
How do you use a loop/if statement to generate a range for vector A. Vector A can be changed by the user but the code should check if the components of the vectors are within -100 to 100
%vector A is defined as :
%A = [-10:0.5:10] ;
A = [1 2 101];
B =[]; % start with empty B
% check if the contents of A are in the range of -100 to 100
max = 100;
min = -100;
if (A>=min)|(A<=max)
for i=[1:length(A)]
% append cube of A(i) to B
B = [B A(i)*A(i)*A(i)];
end
%display B
disp(B);
%display that code is invalid
else
fprintf("Invalid - not within range")
end
  2 件のコメント
Jos (10584)
Jos (10584) 2019 年 3 月 21 日
Did you check the output of (A>=min)|(A<=max) ?
Note that the IF statement converts this condition to a single True or False.
madhan ravi
madhan ravi 2019 年 3 月 21 日
fprintf('Within Range %d\n',A(A>=Min&A<=Max))
fprintf('Not Within Range %d\n',A(~(A>=Min&A<=Max)))
I used if A(A>=min&A<=max)
and got 1 8 1030301
but somehow im suppossed not to cube the components not within the range
A>=Min & A<=Max % index it with A and raise it to the power of three

サインインしてコメントする。

採用された回答

Jos (10584)
Jos (10584) 2019 年 3 月 21 日
I am a little confused by your problem, but here are my thoughts. You might want to use the function ANY, or its sibling ALL, or apply logical indexing
A = [1 2 101]
if any(A > 100)
disp('At least one element of A is larger than 100.') ;
end
B = nan(size(A))
tf = A <= 100 % use logical indexing
B(tf) = A(tf) .^ 3 % only calculate cube for elements of A <= 100, other elements are NaN

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by