How to match cell values across variables

9 Ansichten (letzte 30 Tage)
In-chan Kim
In-chan Kim am 9 Jun. 2020
Beantwortet: ag am 12 Mär. 2025 um 15:52
I've got a table where each row is a separate result, and 2 of the variables (Qstay, indvparkingtype) in there are doubles. The 2 variables correspondingly have the same size, but differs from result to result.
Across all the results, I want to sum up the values in one variable, matched to a value in the other variable.
The variable to be matched to (indvparkingtype) has about 10 different values, let's say [1,2,3...], and I want to sum for each value of indvparkingtype, the Qstay.
So for all instances where scenarioID=1, I would want to find the total Qstay for indvparkingtype=1, =2, =3 etc.
E.g. for indvparkingtype=6, I would want to add 0.2859+0+0.4516+0+0+6.1387+0+2.3656+0.7961+... etc
And to summarise so to have the sums for all values of indvparking type

Antworten (1)

ag
ag am 12 Mär. 2025 um 15:52
Hi Kim,
To get the sum of all "Qstay" values where the "indvparkingtype" matches the required ID, you can use nested loops to iterate over each row of both "Qstay" and "indvparkingtype." This will allow you to sum the values based on the condition.
Below is the MATLAB code snippet demonstrating the approach:
% Assume Qstay and indvparkingtype are cell arrays where each cell contains a vector
% Unique parking types
uniqueTypes = unique([indvparkingtype{:}]);
% Initialize array to store sums
sumArr = zeros(size(uniqueTypes));
% Loop over each unique parking type
for i = 1:length(uniqueTypes)
currID = uniqueTypes(i);
currSum = 0;
% Loop over each row in the data
for j = 1:length(Qstay)
% Access individual arrays in the cell
currQstay = Qstay{j};
currIndvparkingtype = indvparkingtype{j};
% Sum Qstay values where indvparkingtype matches currID
for k = 1:length(currIndvparkingtype)
if currIndvparkingtype(k) == currID
currSum = currSum + currQstay(k);
end
end
end
% Store the sum for the current parking type
sumArr(i) = currSum;
end
Hope this helps!

Kategorien

Mehr zu Special Functions 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