Multiplying Vector by Constant that Depends on Vector Elements

6 Ansichten (letzte 30 Tage)
Kyle
Kyle am 2 Nov. 2011
Given a vector containing values 1 through 1000, I would like to multiply the vector elements by constant C1 if they range from 1-100, by constant C2 if they range from 100-200, etc...
Is there a simpler way to do this than iterating through the vector?
for i = 1:size(vector,2);
if vector(i) < 100
C = C1;
else if vector(i) < 200
C = C2;
end
result(i) = vector(i) * C;
end

Akzeptierte Antwort

Jan
Jan am 2 Nov. 2011
Mult = ones(size(vector));
Mult(vector < 200) = C2; % The largest limit at first!
Mult(vector < 100) = C1;
result = vector .* Mult;
  2 Kommentare
Jan
Jan am 3 Nov. 2011
There have been some other good solutions which perform the distribution to the different intervals automatically. Unfortunately they have been deleted.
The 2nd output of HISTC could be useful also.
Andrei Bobrov
Andrei Bobrov am 3 Nov. 2011
vector=randi([1 100],38,1);
[~,b] = histc(vector,0:100:1000);
C = randi(125,10,1);
result = C(b).*vector;

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by