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

2 views (last 30 days)
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

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 5 Mar 2019
c = 12000;
k = (1:20)';
soc = k*c/numel(k);
lo = ismember(round(data(:,16)),soc);
ocv = data(lo,14);
  1 Comment
Sreekanth Nandakumar
Sreekanth Nandakumar on 7 Mar 2019
Edited: Sreekanth Nandakumar on 7 Mar 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.

Sign in to comment.

More Answers (2)

Bob Thompson
Bob Thompson on 4 Mar 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 Comment
Sreekanth Nandakumar
Sreekanth Nandakumar on 5 Mar 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).

Sign in to comment.


Fangjun Jiang
Fangjun Jiang on 4 Mar 2019
find() could find more than one match. See "help find"

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!