Info
この質問は閉じられています。 編集または回答するには再度開いてください。
Help converting an array to a matrix with 5 columns
1 回表示 (過去 30 日間)
古いコメントを表示
I have been working on a script for a while and am towards the tail end of it. I need to convert the array that goes from 1:number to a matrix that has 5 columns. I can't seem to figure out how to do it. If anyone can help me please help out. Here is my code:
% clear
clear
% clc
clc
name=input('Enter name:','s');
% Ask user to input name
number=input('Enter a whole number between 1 and 100:');
% Ask user for a whole number between 1 and 100
while number<1 || number>100 || round(number)~=number
% a while function that performs actions under if number doesn't meet
% specifications
display('Not a valid number please try again');
number=input('Enter a whole number between 1 and 100:');
end
% End while loop
array=[1:number]
% Create array from 1 to input number
entryposition=0
% Set entry position to 0 for start of loop below
arraylength=length(array)
% Create arraylength variable to help find every multiple of 3
for i = 1:arraylength
% For loop to make each multiple of 3 negative in final array
entryposition=(entryposition+1);
% Cause array to go up by 1 until it meets the input
if mod(array(entryposition),3)==0;
% Check for multiples of 3
array(entryposition)=array(entryposition)*-1;
% Make 3's negative
end
end
disp(array)
disp('Thank you!')
disp(name)
% Thank user for running code
1 件のコメント
James Tursa
2020 年 1 月 30 日
編集済み: James Tursa
2020 年 1 月 30 日
You could use reshape( ), possibly with a transpose. But what if the number of elements in the array is not a multiple of 5?
Also, you don't need the entryposition variable ... just use the index i directly.
Finally, you might look at the result of array(3:3:end) and that could give you a hint on how to vectorize this code instead of using a loop.
回答 (1 件)
Vinai Datta Thatiparthi
2020 年 2 月 3 日
Hey James,
From the description you've provided, this could be a possible solution -
(To echo @James' notes, if the variable number is not a multiple of 5, I've used zero-padding)
array = 1:number;
numRows = ceil(number/5);
arrayNew = [array zeros(1, numRows*5 - number)];
reshape(arrayNew, [numRows, 5])
Also, note that the output value of reshape will follow the column-major order.
Hope this helps!
0 件のコメント
この質問は閉じられています。
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!