How do I add certain numbers from one cell to another?

조회 수: 2 (최근 30일)
Austin Sowers
Austin Sowers 2019년 5월 1일
답변: Pratik 2025년 1월 2일
CA = {[5 -10 2],[6 6 8],[0 9 -10 8 -10 3]};
CB = {[4 17 2],[6 6 10],[9 3 4 9 7 6]};
CC = {[1 2 4],[4 2 1],[1 7 3 1 2 2]};
for i = 1:length(CA)
idx = CA{i}==-10 ;
CB{i}(idx) = CB{i}(idx)+15 ;
end
The output I want is the "new" CB generated in the for loop. But now instead of adding 15 to all of them, I want to add different numbers to each depending on "CC."
For example:
Just looking at the first group of each cell:
CA = {[5 -10 2]}
CB = {[4 17 2]}
CC = {[1 2 4]}
I would like to add the difference between the "1 and 4" in CC (l1-4l=3), to the "17" in CB.
So the first group in the "new" CB will be {[4 20 2]}.
BTW. I chose the numbers "1 and 4" in CC because they are the numbers that would be adjacent to the -10 in CA.

답변 (1개)

Pratik
Pratik 2025년 1월 2일
Hi Austin,
To achieve the desired outcome, you need to identify the indices of -10 in CA, then find the adjacent numbers in CC at those indices, calculate their absolute difference, and add this difference to the corresponding elements in CB. Here's how you can implement this:
CA = {[5 -10 2], [6 6 8], [0 9 -10 8 -10 3]};
CB = {[4 17 2], [6 6 10], [9 3 4 9 7 6]};
CC = {[1 2 4], [4 2 1], [1 7 3 1 2 2]};
for i = 1:length(CA)
idx = find(CA{i} == -10); % Find indices of -10 in CA{i}
for j = 1:length(idx)
if idx(j) > 1 && idx(j) < length(CC{i})
% Calculate the absolute difference of adjacent numbers in CC
difference = abs(CC{i}(idx(j) - 1) - CC{i}(idx(j) + 1));
% Add this difference to the corresponding element in CB
CB{i}(idx(j)) = CB{i}(idx(j)) + difference;
end
end
end
% Display the modified CB
disp(CB);
{[4 20 2]} {[6 6 10]} {[9 3 10 9 8 6]}
Explanation:
  • Finding Indices:
  • Use find(CA{i} == -10) to locate indices of -10 in each cell array within CA.
  • For each index of -10, check if it is not the first or last element to ensure it has adjacent elements.
  • Calculate the absolute difference between the adjacent elements in CC.
  • Add the calculated difference to the corresponding element in CB.

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by