can someone check the code i have problem
4 views (last 30 days)
Show older comments
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 .
Accepted Answer
Dyuman Joshi
on 26 Jan 2023
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
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!