Trouble making a loop repeat correctly
Afficher commentaires plus anciens
I am currently trying to solve this homework question:
This is the code I have written so far:
function y = my_insertation(x,N,m)
% only works for row matrices
% places an m amount of 0's every N places in the initial matrix
% determining size of inputted matrix
sizex = size(x);
% determining number of columns or places in the matrix
sx = sizex(2);
% initializing a matrix of zeroes with zeros
y = zeros(1,(sx+(sx*m)/N));
% determining size of created matrix
sizey = size(y);
% determining number of columns or places in matrix
sy = sizey(2);
% setting counters to 1
j = 1; % counter to place numbers of x into y
% loop that will count and add places into y matrix until full
for i = 1:(sy) % i can only go from 1 to the max amount of indexes
if i == N + 1 % determines when to place m 0's every N spaces
N_old = N
for k = 1:m % repeats placing 0's m times
y(i) = 0; % placing a zero at i
i = i + 1; % adding to the counter i
end
N = 2*N_old + m; % determining new N that will be used for the...
... next if statement
else
y(i) = x(j); % places original place of x matrix assuming the...
... function has not ended from max amount of j
j = j + 1; % increasing counter for j
i = i + 1; % increasing counter for i
end
if j == sx + 1 % failsafe to end the for loop
break
end
end
end
I think most of it is correct, and I feel pretty good about it. But I believe the one part where the code is messing up is at the point where I tell it to do the for k = 1:m. It isn't placing 0 into the y matrix twice like I'm expecting it to. I'm kind of at the end of my rope here and I don't quite know how to fix it from here.
This part specifically is where I believe it is running into problems.
if i == N + 1 % determines when to place m 0's every N spaces
N_old = N
for k = 1:m % repeats placing 0's m times
y(i) = 0; % placing a zero at i
i = i + 1; % adding to the counter i
end
N = 2*N_old + m; % determining new N that will be used for the...
... next if statement
else
y(i) = x(j); % places original place of x matrix assuming the...
... function has not ended from max amount of j
j = j + 1; % increasing counter for j
i = i + 1; % increasing counter for i
end
I would appreciate any help you could provide me, I appreciate it.
As a check, I have been using this script:
clear all
close all
clc
x = [1,3,7,2,4,9]
N = 3;
m = 2;
my_insertation(x,N,m)
% should equal the following function
xsolution = [1,3,7,0,0,2,4,9,0,0]
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!