필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2019년 3월 5일
c = 12000;
k = (1:20)';
soc = k*c/numel(k);
lo = ismember(round(data(:,16)),soc);
ocv = data(lo,14);
  댓글 수: 1
Sreekanth Nandakumar
Sreekanth Nandakumar 2019년 3월 7일
편집: Sreekanth Nandakumar 2019년 3월 7일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Bob Thompson
Bob Thompson 2019년 3월 4일
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
Sreekanth Nandakumar
Sreekanth Nandakumar 2019년 3월 5일
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).

댓글을 달려면 로그인하십시오.


Fangjun Jiang
Fangjun Jiang 2019년 3월 4일
find() could find more than one match. See "help find"

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by