Assigning specific elements of vector a different value

19 ビュー (過去 30 日間)
Morgan Roberts
Morgan Roberts 2018 年 1 月 10 日
Hi
I am trying to assign values to elements from one vector based on the values of another vector:
r = [1,3,4,5,3,3,4,5,6,4];
Postdia = [12,20]
For vector r, I want to pull out the element when the sum of r reaches 12 (Postdia First value) - and name it SYNAPSE. Similarly I want to pull out the element in r when the sum of the values reaches 20 (Postdia second value) - call it SYNAPSE also. The other values should all be assigned NO SYNAPSE.
For this I have written this code but it isn't working.
b= 0;
b2 = 0;
r = [1,3,4,5,3,3,4,5,6,4];
Postdia = [12,20]
r2 = r;
k = 0
for i = 1:length(r)
b = r(i) + b;
for j = 1:2
b2 = find(b > Postdia(j));
r2(i) = r(b2);
if b2 == 1
r2(i) = {'SYNAPSE'};
else
r2(i) = {'NO SYNAPSE'};
end
end
end
Does anyone have any suggestions?
Cheers
  2 件のコメント
James Tursa
James Tursa 2018 年 1 月 10 日
What do you want for a result? A cell array the same size as r, but with either 'SYNAPSE' or 'NO SYNAPSE' for the elements depending on your criteria?
Morgan Roberts
Morgan Roberts 2018 年 1 月 10 日
Yes that exactly

サインインしてコメントする。

採用された回答

Star Strider
Star Strider 2018 年 1 月 10 日
See if this works for you:
r = [1,3,4,5,3,3,4,5,6,4]; % Given Data
Postdia = [12,20]; % Given Data
r2 = repmat({'NO SYNAPSE'}, 1, numel(r)); % Create ‘r2’
csr = cumsum(r); % Cumulative Sum
lm = bsxfun(@le, csr, Postdia'); % Logic Matrix
[~,idx] = max(fliplr(lm),[],2); % Numerical Indices
r2(numel(r)-idx'+2) = {'SYNAPSE'}; % Desired Output
r2 =
1×10 cell array
Columns 1 through 5
{'NO SYNAPSE'} {'NO SYNAPSE'} {'NO SYNAPSE'} {'SYNAPSE'} {'NO SYNAPSE'}
Columns 6 through 10
{'NO SYNAPSE'} {'SYNAPSE'} {'NO SYNAPSE'} {'NO SYNAPSE'} {'NO SYNAPSE'}
Experiment to get the result you want.
  1 件のコメント
Patel jaykumar Dipakbhai
Patel jaykumar Dipakbhai 2019 年 7 月 8 日
dear star strider, what if i want to assign specific values to each elements of the coloumn vector (v1)and same thing i want to do for another coloumn vectors(v2)? the values i want to assign are different for both coluomn vectors.
now after assigning the values to the both coloumn vectors what should i do 'to add the values of the respective column vectors' when the element of standard column vector (v1) is equal to the element of the v2?

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by