i need some help on matrix operations!

1 次查看(过去 30 天)
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?

采纳的回答

sixwwwwww
sixwwwwww 2013-12-2
编辑:sixwwwwww 2013-12-2
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 个评论
sixwwwwww
sixwwwwww 2013-12-2
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

请先登录,再进行评论。

更多回答(2 个)

Azzi Abdelmalek
Azzi Abdelmalek 2013-12-2
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 2013-12-2
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

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

Start Hunting!

Translated by