Moving a value from one row vector to another row vector

5 Ansichten (letzte 30 Tage)
Thomas
Thomas am 15 Feb. 2016
Beantwortet: Walter Roberson am 15 Feb. 2016
I am trying to move a value from a specified number of columns in a row vector to another specified number of columns in another row vector. I've been using two while loops, one for addition and the other for subtraction. When I use the subtraction loop its seems to stop at one column and give a huge negative number. For the purposes of what I am trying to do I need it to go to the next column if there is a zero (I haven't worked how to do this yet). Anyway here is the code I am currently using,
%
Z = (1:24); % example row vectors
X = linspace(1,500,24);
A = sum(X([17:19])); % quantity that is going to be subtracted from X and added to Z
A1 = A; % value used for second while loop
B = [1:8 22:23]; % location that A will be distributed to
C = [17:19]; % location that A will be subtracted from
B_increment = A/length(B); % quantity of A to be distributed per a column
ind = 1;
while A >= B_increment
Z(1, B(ind)) = Z(1, B(ind)) + B_increment;
A = A - B_increment;
ind = ind + 1; % move to the next value
if ind>length(Z(1, B))
break
end
end
ind2 = 1; %for second while loop
C_increment = A1/length(C);
while A1 >= C_increment;
X(1, C(ind2)) = X(1, C(ind2)) - C_increment;
A1 = A1 - C_increment;
ind2 = ind2 + 1;
if ind2>length(X(1, C))
break
end
end
The result of the above while loops is the X vector to have [-21, 0, 21] at the specified columns but I want it to be zero for each column. The addition loop appears to be working correctly.
I am writing this script to work with various row vectors of the same dimensions (1x24) but with different numbers.
Am I on the right track and if so is there any advice on how to ensure that none of the values will ever be zero or is there a simpler way to do this?

Antworten (1)

Walter Roberson
Walter Roberson am 15 Feb. 2016
With regarding to changing columns:
colnum = 1;
while colnum <= 20
if data(colnum) >= 3
data(column) = data(column) - 1;
colnum = max(1, colnum - 7);
else
colnum = colnum + 1;
end
end
This shows progression by 1 column normally but if a particular value is detected (>=3 in this example) then the column number is changed to something else (7 columns back in this example).
This is not intended to be code to do whatever you are doing: it is code intended to illustrate how you could switch columns.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by