# How do I add values to an array on a conditional basis?

2 views (last 30 days)
Cai Chin on 25 Dec 2020
Commented: Cai Chin on 26 Dec 2020
Hi, I am trying to add values to a pre-allocated array based on whether the row number belongs to a set of values. In this example, I have generated an array with 7 rows and 900 columns, and only when the row number of another array matches the numbers in a specified vector, do I want the column values from that array to be added to my new array. At the moment, it keeps changing the dimension of the array so I am left with zeros in several of the unfilled positions. Any suggestions would be greatly appreciated, thanks in advance.
abnormal_cycles_5 = [95, 94, 92, 91, 79, 72, 1];
values_v_5_abnormal = zeros(length(abnormal_cycles_5), 900);
values_w_5_abnormal = zeros(length(abnormal_cycles_5), 900);
for i = 1:95
if ismember(i, abnormal_cycles_5)
values_v_5_abnormal(i, 1:900) = values_v_5(i, 1:900);
values_w_5_abnormal(i, 1:900) = values_w_5(i, 1:900);
end
end
I have attached the variable values 'values_v_5' and 'values_w_5':

Image Analyst on 25 Dec 2020
Do you mean like this:
abnormal_cycles_5 = [95, 94, 92, 91, 79, 72, 1]; % 7 columns, 1 row
values_v_5_abnormal = zeros(length(abnormal_cycles_5), 900); % 7 rows, 900 columns.
values_w_5_abnormal = zeros(length(abnormal_cycles_5), 900); % 7 rows, 900 columns.
values_w_5_abnormal(:, abnormal_cycles_5) = repmat(abnormal_cycles_5', 1, 7);
where the 7 element vector "abnormal_cycles_5" gets loaded into columns 95, 94, 92, 91, 79, 72, and 1 of the 2-D matrix "values_w_5_abnormal"?
Cai Chin on 26 Dec 2020
Yes, thank you very much!