Only the value corresponding to the last loop of a for loop being saved in the output array

2 Ansichten (letzte 30 Tage)
Hello,
I have the below problem regarding for loop.
I am trying to save the result of values of a statement inside a for loop. But the output array is only saving the calculation of the last loop. Can anyone please help me on how to solve this issue? I am posting my code below.
data=xlsread('22245_1.xlsx');
Cap = 12000; % I have initialized a value here
Volt=data(:,14); % I wanted to separate single column arrays for easy coding since the main file has 36000 rows and 20 coumns
C_Chge=round (data(:,16));
C_dis=data(:,17);
SOC=zeros(1,20);
perc = 1:20;
N=numel(perc);
OCV = zeros(N,1);
for k=1:N
SOC = (k*Cap)/20
A = find(C_Chge(:,1)== SOC);
OCV(k)=Volt(A); % I am getting an error with this statement - Unable to perform assignment because the left and right sides have a different number of elements.
end

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 5 Mär. 2019
c = 12000;
k = (1:20)';
soc = k*c/numel(k);
lo = ismember(round(data(:,16)),soc);
ocv = data(lo,14);
  1 Kommentar
Sreekanth Nandakumar
Sreekanth Nandakumar am 7 Mär. 2019
Bearbeitet: Sreekanth Nandakumar am 7 Mär. 2019
I am sorry for the late reply. Even this does not work. The OCV is giving me an array of Zeros
Edited: I am sorry. This works. :) I was wrongly looking into OCV ( with capitals). Thank you very much.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Bob Thompson
Bob Thompson am 4 Mär. 2019
You're getting the error because OCV(k) is a single element, and I suspect that Volt(A) is not.
For the problem of only getting results from the last loop, you need to index your results within the loop to be saved with each loop iteration. Here I have set the results from each iteration to form a 3D dimension of the interior elements.
for k=1:N
SOC(:,:,k) = (k*Cap)/20
A(:,:,k) = find(C_Chge(:,1)== SOC(:,:,k));
OCV(:,:,k)=Volt(A(:,:,k));
end
  1 Kommentar
Sreekanth Nandakumar
Sreekanth Nandakumar am 5 Mär. 2019
This is not working for me. What I exactly need is to find the row number of a value in the array C_Chge ( the value is calculated by the formula for SOC) and then get the corresponding value lying in the same row number in the array OCV. I need to get the corresponding OCV value for 20 different C_Chge values (which must be caluculated in loop).

Melden Sie sich an, um zu kommentieren.


Fangjun Jiang
Fangjun Jiang am 4 Mär. 2019
find() could find more than one match. See "help find"

Kategorien

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

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by