can someone check the code i have problem
1 次查看(过去 30 天)
显示 更早的评论
Hello!
I have a matrixR(6x30) contains one value by row,the sum of R colomns is given by A, each value of A has a corresponding element in a vector B :
A = [7;5;7;5;5;7]
B = [4;6;4;6;6;4]
in order to transform each value in B to a column vector ,i generated a matrix C where the number of columns is the max value of B as follow
C =
0 1 2 3 4 0
0 1 2 3 4 5
0 1 2 3 4 0
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 0
After this I returned to matrix R and finding the index of the value corresonding to A, and start fill the the next elements until finish the elements of each vector of C,
this is my code for generating C
k = max(B);
C = zeros(size(B,1),k);
for i = 1:size(B,1)
ins = B(i);
compteur = 0;
for j =1:ins
C(i,j) = compteur;
compteur = compteur +1;
end
end
and to fill elements of R, starting to the first nonzero until the number of element existing in each corresponding value in C,
m = 6;
n = 30;
L = 2000;
Req = zeros(m,n);
for i = 1:m
for j =1:n
if R(i,j) ~= 0
start = find(R(i,:)~=0,1); %find index of first value
End = start+size(C,2); % number of columns to fill
end2 = size(C,2);
for jj=1:jend2
gg = (L*C(1,jj))/B(i); % value in each column
Req(i,start) = gg;
start = start + 1;
end
end
end
end
the problem with this code is the number of element exceed the needed interval, but i want to fill just the number of element from the first value until the number of element in C without considering last zeros.
any suggestion is appreciated .
2 个评论
Dyuman Joshi
2023-1-26
编辑:Dyuman Joshi
2023-1-26
What exactly are you trying to do? Are you trying to obtain the elements of R from given conditions? It would be helpful in knowing what your desired output is.
The C matrix you have shown above is not same as the output from the code, I assume that is a typo?
B = [4;6;4;6;6;4];
k = max(B);
C = zeros(size(B,1),k);
for i = 1:size(B,1)
ins = B(i);
compteur = 0;
for j =1:ins
C(i,j) = compteur;
compteur = compteur +1;
end
end
C
Also, it would be helpful if you could attach or provide the data for R.
You can also improve your code by vectorizing it at some points
B = [4;6;4;6;6;4];
k = max(B);
C = zeros(size(B,1),k);
for i = 1:size(B,1)
ins = B(i);
C(i,1:ins)=0:ins-1;
end
C
采纳的回答
Dyuman Joshi
2023-1-26
You can do that without defining C (If I understand what you want to do correctly)
B = [4;6;4;6;6;4];
m = 6;
n = 30;
L = 2000;
Req = zeros(m,n);
for idx=1:m
%since you have only 1 non-zero per row
first=find(R(idx,:))
%use the value as an index
last=min(n,first+B(idx)-1)
%modify Req accordingly
Req(idx,first:last)=R(idx,first)*(0:(last-first))/B(idx)
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!