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?
0 个评论
采纳的回答
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
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
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)
0 个评论
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!