Azzera filtri
Azzera filtri

i need some help on matrix operations!

1 visualizzazione (ultimi 30 giorni)
mary
mary il 2 Dic 2013
Risposto: Image Analyst il 2 Dic 2013
if i have the index matrix a
a=[0 1 0 1 1 0 1]
and matrix b contains the actual values
v=[2 3 4 2 6 1 8]
here i'm going to check if a(i)=1 then i'm going to do the following:
a(2)=1 then sum=v(4)+v(5)+v(7)
and this will be done again to each one alone..
how to do that in an optimal way?

Risposta accettata

sixwwwwww
sixwwwwww il 2 Dic 2013
Modificato: sixwwwwww il 2 Dic 2013
do you need something like this:
a=[0 1 0 1 1 0 1];
v=[2 3 4 2 6 1 8];
for i = 1:numel(a)
sum = 0;
for j = i:numel(a)
if a(j) == 1
sum = sum + v(j);
end
end
sumArray(i) = sum;
end
  3 Commenti
sixwwwwww
sixwwwwww il 2 Dic 2013
mary try this:
a = [1 0 1 1];
v = [2 3 4 5];
sumArray = zeros(1, numel(a));
for i = 1:numel(a)
if a(i) ~= 0
for j = 1:numel(a)
if a(j) == 1 && j ~= i
sumArray(i) = sumArray(i) + v(j);
end
end
end
end
mary
mary il 2 Dic 2013
yea that worked thanks

Accedi per commentare.

Più risposte (2)

Azzi Abdelmalek
Azzi Abdelmalek il 2 Dic 2013
a=[1 0 1 1];
v=[2 3 4 5];
idx=find(a);
n=numel(idx);
ii=cell2mat(arrayfun(@(x) circshift(idx,[0 -x]),(1:n)','un',0));
s=sum(v(ii(:,1:n-1)),2)

Image Analyst
Image Analyst il 2 Dic 2013
Mary, a vectorized, more "MATLAB-ish" way of doing it is:
% Make logical matrix.
a= logical([0 1 0 1 1 0 1])
% The "v" matix.
v = [2 3 4 2 6 1 8]
%------------------------------------------------
% Initialize
partialSum = a .* (sum(v(a)) * ones(1, length(a)))
% Subtract the v value
partialSum(a) = partialSum(a)-v(a)
In the command window, you'll see:
a =
0 1 0 1 1 0 1
v =
2 3 4 2 6 1 8
partialSum =
0 19 0 19 19 0 19
partialSum =
0 16 0 17 13 0 11

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Non è stata ancora inserito alcun tag.

Community Treasure Hunt

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

Start Hunting!

Translated by