Clear Filters
Clear Filters

i need some help on matrix operations!

1 view (last 30 days)
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?

Accepted Answer

sixwwwwww
sixwwwwww on 2 Dec 2013
Edited: sixwwwwww on 2 Dec 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 Comments
sixwwwwww
sixwwwwww on 2 Dec 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 on 2 Dec 2013
yea that worked thanks

Sign in to comment.

More Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 2 Dec 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 on 2 Dec 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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!